text stringlengths 37 1.41M |
|---|
class Solution:
def wiggleMaxLength(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if not nums:
return 0
# up[i] is the length of a longest wiggle subsequence of {nums[0],...,nums[i]}, with a
# positive difference between its last two numbe... |
class Solution:
def searchMatrix(self, matrix, target):
"""
:type matrix: List[List[int]]
:type target: int
:rtype: bool
"""
if not matrix or not matrix[0]:
return False
firstNumbers = [nums[0] for nums in matrix]
# find r... |
class Solution:
def asteroidCollision(self, asteroids):
"""
:type asteroids: List[int]
:rtype: List[int]
"""
asteroidStack = [] # stores the survival asteroid
for asteroid in asteroids:
asteroidStack.append(asteroid)
while len(asteroidStack) >=... |
class Solution:
def findCircleNum(self, M):
"""
:type M: List[List[int]]
:rtype: int
"""
def findCircleNumHelper(node):
visitedNodes.add(node)
for neighborNode in range(len(M)):
if M[node][neighborNode] == 1:
if neig... |
# Definition for singly-linked list with a random pointer.
# class RandomListNode(object):
# def __init__(self, x):
# self.label = x
# self.next = None
# self.random = None
class Solution(object):
def copyRandomList(self, head):
"""
:type head: RandomListNode
:rt... |
"""Unittest for linkedlist."""
import unittest
import linkedlist
class LinkedListTest(unittest.TestCase):
def test_add(self):
ll = linkedlist.LinkedList()
for i in range(10):
ll.add(i)
self.assertEqual(len(ll), 10)
def test_pop(self):
ll = linkedlist.LinkedList()... |
"""Defines a binary search tree."""
class Node(object):
def __init__(self, value):
self._left = self._right = None
self.value = value
def add(self, value):
if value <= self.value:
if self._left is None:
self._left = Node(value)
else:
... |
import math
def SubarrayProduct(numbers, k):
subsets = []
for i in range(len(numbers)):
subsets.append([numbers[i]])
for j in range(i + 1, len(numbers)):
subset = subsets[-1]
curr_subset = subset + [numbers[j]]
subsets.append(curr_subset)
counter = 0
... |
import sqlite3
conn = sqlite3.connect('customer.db')
c = conn.cursor() #creating a cursor
#creating a table
c.execute("""CREATE TABLE customers (
first_name text,
last_name text,
email text
)""")
#DATYPES (NULL,INTEGER,REAL,TEXT,BLOB)
conn.commit()
conn.close()
|
#!/usr/bin/env python
languages = ['python', 'java', 'C++', 'PHP']
for language in languages:
print language, "rocks!"
dict = {"name":"Jesse","location":"Denver","favorite site":"tutsplus"}
for key in dict:
print "His ", key, "is", dict[key]
print range(10)
for int in range(10):
print "int =", int
if int == ... |
import sys
# https://stackoverflow.com/questions/5324647/how-to-merge-a-transparent-png-image-with-another-image-using-pil
image1 = '8fe92c97.jpg'
image2 = 'botgarden_watermark_520x520_trans_white.png'
from PIL import Image
if 'paste' in sys.argv:
background = Image.open(image1)
foreground = Image.open(ima... |
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
if l1 is None or l2 is None:
return l1 or l2
node1 = l1
node2 = l2
... |
# 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 levelOrderBottom(self, root: TreeNode) -> List[List[int]]:
def dfs(root, level, results=[]):
... |
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def reverseList(self, head: ListNode) -> ListNode:
head_copy = head
if head is None or head.next is None:
return head
prev_node = head
... |
# 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 levelOrderBottom(self, root: TreeNode) -> List[List[int]]:
# bfs + queue
if not root:
... |
# 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 sumOfLeftLeaves(self, root: TreeNode) -> int:
if not root:
return 0
results... |
# 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 postorderTraversal(self, root: TreeNode) -> List[int]:
if not root:
return []
... |
class Solution:
def sortedSquares(self, A: List[int]) -> List[int]:
if len(A) == 0 or len(A) == 1:
return [x ** 2 for x in A]
left = 0
right = len(A) - 1
tmp = []
while left <= right:
if A[left] ** 2 <= A[right] ** 2:
tmp.append(A[ri... |
# Actually same with solution_1, but it's more concise
# 实际上和solution_1很相似,只是更简洁
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def reverseList(self, head: ListNode) -> ListNode:
prev = None
curr = head
... |
class Solution:
def permute(self, nums: List[int]) -> List[List[int]]:
results = []
length = len(nums)
def back_track(tmp_result):
if len(tmp_result) == length:
results.append(tmp_result[:])
return
for num in nums:
i... |
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# ... |
# using two pointers
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def hasCycle(self, head: ListNode) -> bool:
fast_p = slow_p = head
while fast_p and fast_p.next:
slow_p = slow_p.next # m... |
# 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 getAllElements(self, root1: TreeNode, root2: TreeNode) -> List[int]:
def in_order(root):
... |
# 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 constructFromPrePost(self, pre: List[int], post: List[int]) -> TreeNode:
if not pre:
... |
class Solution:
def canVisitAllRooms(self, rooms: List[List[int]]) -> bool:
def bfs(start_node):
visited = set()
my_queue = [start_node]
visited.add(start_node)
results = []
while my_queue:
curr_top = my_queue.pop(0)
... |
class Solution:
def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]:
return list(set(nums1) & set(nums2))
"""
Results:
Runtime: 60 ms, faster than 36.37% of Python3 online submissions for Intersection of Two Arrays.
Memory Usage: 13.9 MB, less than 78.12% of Python3 online submissions f... |
# 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 zigzagLevelOrder(self, root: TreeNode) -> List[List[int]]:
def bfs(root):
queue = [... |
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def maxDepth(self, root: TreeNode) -> int:
# Recursive DFS
if not root:
return 0
max_depth = 1
... |
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def reversePrint(self, head: ListNode) -> List[int]:
if not head:
return []
sub_result = self.reversePrint(head.next)
sub_result.append(... |
class Solution:
def nextGreaterElement(self, nums1: List[int], nums2: List[int]) -> List[int]:
my_stack = []
my_dict = {}
for num in nums2:
while my_stack and my_stack[-1] < num:
top_num = my_stack.pop(-1)
my_dict[top_num] = num
my_st... |
#!/usr/bin/env python
# coding: utf-8
# # Exploratory Data Analysis: SuperStore Dataset
# # Anika Bizla
# # Task 3
# In[51]:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
# ## Reading the Dataset
# In[52]:
df=pd.read_csv("/Users/anikabizla/Downloads/SampleSuperstore.csv")
df.head()
... |
#Uses python3
import sys, functools
def largest_number(a):
res = ""
a = sorted(a, key=functools.cmp_to_key(compare))
for x in a:
res += x
return res
def compare(x, y):
xy = int(str(x) + str(y)); yx = int(str(y) + str(x))
if xy > yx:
return -1
elif yx > xy:
return... |
array = [3,7,8,1,5,9,6,10,2,4]
def quick_sort(arr):
print("초기 입력값 : " , arr)
if len(arr) < 2:
return arr
pivot = arr[len(arr) // 2]
left_arr, equal_arr, right_arr = [], [], []
for i in arr:
if i < pivot :
left_arr.append(i)
elif i == pivo... |
class Animal():
def __init__(self):
self.__name = "晨波"
def getname(self):
return self.__name
def eat(self):
print('吃吃吃')
def sleep(self):
print("睡睡睡")
def __money(self):
print('私有财产')
def askmoney(self):
self.__money()
class Dog(Animal):
pass
class Cat(Animal):
pass
taidi = Dog()
taidi.eat()
taid... |
from threading import Thread
import time
import threading
num = 100
def work1():
global g_num
for i in range(100):
num += 1
print(num)
def work2():
global g_num
for i in range(100):
num += 1
print("%st %d"%num)
print("---线程创建之前g_num is %d---"%num)
t1 = Thread(target=work1)... |
from queue import PriorityQueue
import math
class Node:
def __init__(self,intersection_num):
self.intersection_num = intersection_num
self.cumulative_g = None
self.f = None
self.parent = None
self.children = []
self.index = None
def get_intersection_number(... |
#! /usr/bin/env python2
"""
generate square sequence number
simply checking isPrime
"""
class square():
def __init__(self):
self.s = 1
self.l = 2
self.i = 0
def next(self):
"""
>>> sq= square()
>>> [sq.next() for i in range(12)]
[3, 5, 7, 9, 13, 17, 21... |
def sqrt2expan():
a, b = 3, 2
while 1:
yield (a, b)
a, b = a + 2 * b, a + b
def cntDigit(n):
cnt = 0
while n > 0:
cnt += 1
n /= 10
return cnt
sqrt2 = sqrt2expan()
cnt = 0
for i in range(10**3):
a, b = sqrt2.next()
if cntDigit(a) > cntDigit(b):
cnt ... |
import math
def isPrime(n):
if n==1 or n==2:
return True
i=2
thres = math.sqrt(n)
while i<=thres:
if n%i==0:
return False
i += 1
return True
def isCons(lst,i,n):
for j in range(n-1):
if(lst[i+j]+1==lst[i+j+1]):
pass
else:
... |
def isPrime(n):
r = 2
while 1:
if r * r > n:
return True
if n % r == 0:
return False
r += 1
def oldSln():
print sum((i for i in xrange(2, 2000 * 1000) if isPrime(i)))
def sieve(m):
for i in xrange(1, m):
|
N = 10**18
from math import sqrt
def isTarget(n):
n = n / 100
rn = 9
while n:
r = n % 10
if r != rn:
return False
rn -= 1
n = n / 100
if rn == 0:
return True
else:
return False
for i in xrange(int(sqrt(N)) / 10 * 10, int(sqrt(N * 2)... |
"""
Defines the Organism class.
"""
from curdl import CURDL_code
from resources import ResourcesStock
from cells.cell import CentralCell
from cells.cell_types import _cell_types
class Organism:
"""
An organism is a set of cells organised in a 2D grid by its CURDL code, and capable of
gathering and spendin... |
'''
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 written as, XII, which is simply X + II.
The number twenty seven is written as XXV... |
'''
Given an input string (s) and a pattern (p), implement regular expression matching with support for '.' and '*'.
'.' Matches any single character.
'*' Matches zero or more of the preceding element. ==> * wildcard 萬用字元
The matching should cover the entire input string (not partial).
Note:
s could be empty and co... |
'''
Given a string s, find the longest palindromic substring in s.
You may assume that the maximum length of s is 1000.
Example 1:
Input: "babad"
Output: "bab"
Note: "aba" is also a valid answer.
Example 2:
Input: "cbbd"
Output: "bb"
'''
# class Solution:
# def longestPalindrome(self, s: str... |
from tkinter import *
a = 0
b = 0
def chageText(num):
lab["text"] = lab["text"] + num
window = Tk()
window.title("cool")
window.geometry("400x350+100+50")
window.config(bg="lightgreen")
window.rowconfigure(1,weight = 1)
window.rowconfigure(2,weight = 1)
window.rowconfigure(3,weight = 1)
window.ro... |
# the symbol of element
def make_sentence_as_list_of_elemnts(text: str):
return {i: word[0] if i+1 in [1, 5, 6, 7, 8, 9, 15, 16, 19] else word[:2]
for i, word in enumerate(text.strip('.').split(' '))}
if __name__ == '__main__':
text = "Hi He Lied Because Boron Could Not Oxidize Fluorine. New Natio... |
# Make an if statement to go to the end of the game.
x = input("")
if x == "a":
Game()
else:
print("e")
class Game:
def __init__(self):
# End Frame
self.end_box = Toplevel()
self.end_frame = Frame(self.end_box)
self.end_frame.grid(row=0)
# Heading row 0
se... |
"""
Performs hybrid filtering based upon a list of movies supplied
by the app user.
Parameters
----------
movie_list : list (str)
Favorite movies chosen by the app user.
top_n : type
Number of top recommendations to return to the user.
Returns
-------
list (str)... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
print 'Exercise 1'
keimeno=raw_input ("Πληκτρολογήστε το κείμενό σας:")
while len(keimeno)==0:
keimeno=raw_input ("Πληκτρολογηστε το κείμενό σας:")
print "Το κείμενό σας είναι: " +keimeno
x=list(keimeno)
y=len(x)
for i in range (y):
if(x[i]== '!') and (x[y... |
def compute_time(absolute_seconds):
# compute days, hours, and minutes from seconds.
absolute_minutes = absolute_seconds / 60
days = absolute_minutes / 1440
hours = absolute_minutes / 60 - (days * 24)
minutes = absolute_minutes - (hours * 60) - (days * 24 * 60)
return {'days': days, 'hours': hou... |
# DEBEN DE PONERLE ANOTACION DE TIPO A TODAS LAS FUNCIONES
# 7. Implemente una función que cuente la frecuencia de palabras en una lista.
# La función debe de recibir una lista
# y retornar un diccionario con la palabra (en minúscula) como llave y la cantidad de ocurrencias como valor.
# No se debe de distinguir entre... |
# -*- coding: utf-8 -*-
from itertools import chain
from atores import ATIVO
VITORIA = 'VITORIA'
DERROTA = 'DERROTA'
EM_ANDAMENTO = 'EM_ANDAMENTO'
class Ponto():
def __init__(self, x, y, caracter):
self.caracter = caracter
self.x = round(x)
self.y = round(y)
def __eq__(self, other):... |
"""
// Time Complexity : o(n)
// Space Complexity : o(1)
// Did this code successfully run on Leetcode : yes
// Any problem you faced while coding this : no
// Your code here along with comments explaining your approach
"""
class Solution:
def rev(self, nums, l, h): #function to reverse
while l <... |
import random
HANGMAN = (
"""
------
| |
|
|
|
|
|
|
|
----------
""",
"""
------
| |
| O
|
|
|
|
|
|
----------
""",
"""
------
| |
| O
| -+-
|
|
|
|
|
----------
""",
"""
------
| |
| O
| /-+-
|
|
... |
def sumIntervals(lista):
mhkos=len(lista) #μετραει το μηκος της λιστας
athr=0
lista.sort() #ταξινομει την λιστα
print(lista)
for i in range (0,mhkos):#συγκριση της λιστας μεσα στην for και επιστρεφει το αθροισμα
x1=max(lista[i])
y1=min(lista[i])
athr=athr+(x1-y1)
... |
class Planet(object):
names = ["Mercury","Venus","Earth","Mars", "Jupiter", "Saturn", "Uranus", "Neptune"]
diameters = ["3031.9", "7520.8", "7917.5", "4212.3","86881", "72367", "31518", "30599"]
distances = ["1st","2nd","3rd","4th","5th","6th","7th","8th"]
def __init__(self, name, diameter, distance):
... |
def swap_case_worst(s):
s=list(s)
new_string=[]
for i in range(0,len(s)):
if s[i]==' ':
new_string=new_string+[s[i]]
elif s[i] in "!@#$%^&*()><?}{[].,123456789\"":
new_string=new_string+[s[i]]
elif s[i] in '\"qqwertypasdfghjklzxcvbnmQWERTYUIOPASDFGHJKL... |
class Product():
def __init__(self,name,price,weight,discount):
self.name=name
self.price=price
self.weight=weight
self.discount=discount
def __repr__(self):
return repr((self.name,self.price,self.weight))
def discountPrice(self):
return self.price-(s... |
>>> import collections
>>> d=collections.deque('abcdefg')
>>> d
deque(['a', 'b', 'c', 'd', 'e', 'f', 'g'])
>>> d.appendleft(1)
>>> a
[2, 3, 5]
>>> d
deque([1, 'a', 'b', 'c', 'd', 'e', 'f', 'g'])
>>> d.append(2)
>>> d
deque([1, 'a', 'b', 'c', 'd', 'e', 'f', 'g', 2])
>>> d.pop()
2
>>> d
deque([1, 'a', 'b', 'c', 'd', 'e',... |
#!/bin/python3
import os
import sys
from datetime import time,datetime,date
import datetime
import time
#
# Complete the timeConversion function below.
#strptime
def timeConversion(s):
c=s.split(":")
hour=int(c[0])
minute=int(c[1])
if "AM" in c[2]:
new_second=c[2].rstrip("AM")
if hour=... |
co = float(input('Informe o cateto oposto : '))
ca = float(input('Informe o cateto adjacente : '))
hi = ((ca ** 2) + (co ** 2)) ** (1 / 2)
print('Hipotenusa = {:.2f}' .format(hi))
|
import math
num = float(input("Digite um numero : "))
# inteiro = math.floor(num)
# inteiro = math.trunc(num)
# print("A parte inteira eh = {}" .format(inteiro))
print("A parte inteira eh = {}" .format(int(num)))
|
nome = input('Digite seu nome completo : ').strip()
print('Seu nome transformado para Maiusculo eh :', end=' ')
print(nome.upper())
print('Seu nome transformado para minusculo eh : ', end='')
print(nome.lower())
# print('Seu nome tem {} letras validas'.format(len(''.join(nome.split()))))
print('Seu nome tem {} letras v... |
# Write a class to hold player information, e.g. what room they are in
# currently.
class Player:
def __init__(self, name, room):
self.name = name
self.room = room
self.inventory = []
def __str__(self):
return f"Name: {self.name}\tLocation: {self.room}"
def move_to(self, di... |
input_shape= input("Enter your shape:Triangle ? Rectangle ? Circle ? \n")
input_func= input("Enter your function: Enviroment ? Area \n")
if input_shape== "Rectangle":
tool = float(input("Enter tool\n"))
arz = float(input("Enter arz\n"))
dastoor= input_func
def mostatil (tool, arz, dastoor):
if... |
import random
chosenNumber = random.randint(1, 10)
def guessNumber():
guessedNumber = input("Guess a number between 1 and 10: ")
if str(chosenNumber) == guessedNumber:
print("You guessed right, great job!")
elif guessedNumber.lower() == 'exit':
exit()
elif str(chosenNumber) != guessed... |
#!/usr/bin/env python
"""
Based on https://github.com/opencv/opencv/blob/master/samples/python/mouse_and_match.py
Read in the images in a directory one by one
Allow the user to select two points and then draw a line between them.
When done with the current image press SPACE to show next image. When pressing SPACE it ... |
l1=list(input("Enter the list"))
k=int(input('Enter the subarray length'))
l2=[]
for i in range(0,len(l1)-k+1):
l3=list(l1[i:i+k])
l2.append(max(l3))
print(l2) |
import re
__author__ = 'davidabrahams'
def get_string_from_file(file_name):
"""
:param file_name: a string of the file name to read
:return:= a string of the text within than file
"""
return open(file_name).read()
def is_word_before_all_caps(string, index_of_colon):
"""
>>> is_word_befo... |
def intersection(arrays):
dic = {}
for i in range(0, len(arrays)):
index = 0
while index != len(arrays[i]):
if arrays[i][index] not in dic.keys():
dic[arrays[i][index]] = 1
else:
number = dic[arrays[i][index]]
number += 1
... |
import pandas as pd
def load():
filename = "hotel/sample_hotel_data.csv"
df = pd.read_csv(filename)
data = {
"df": df,
"keys": ["home_city", "dest_city"],
}
data["types"] = {
"distance": float,
"home_pop": int,
"dest_pop": int,
"hotel_size": int,
... |
from random import shuffle
#générateur de pharse
#demander en console une chaine de la forme "mot1/mot2/mot3/mot4
chaine_word = input("Entrer une de la forme mot1/mot2/mot3/mot4")
#transformer cette chaine en liste
word = chaine_word.split("/")
#melanger la phrase
shuffle(word)
#récupérer le nombre d'éléments
word... |
# !/usr/bin/python3
# -*- coding: utf-8 -*-
# @Author: 花菜
# @File: 整数反转.py
# @Time : 2020/12/7 22:18
# @Email: lihuacai168@gmail.com
class Solution(object):
"""
>>> s = Solution()
>>> s.reverse(1534236469)
0
>>> s.reverse(123)
321
>>> s.reverse(120)
21
>>> s.reverse(-123)
-321
... |
# !/usr/bin/python3
# -*- coding: utf-8 -*-
# @Author: 花菜
# @File: 柠檬水找零.py
# @Time : 2020/12/10 00:12
# @Email: lihuacai168@gmail.com
from typing import List
class Solution:
"""
>>> s = Solution()
>>> s.lemonadeChange([5,5,5,10,20])
True
>>> s.lemonadeChange([5,5,10])
True
>>> s.lemona... |
# !/usr/bin/python3
# -*- coding: utf-8 -*-
# @Author:梨花菜
# @File: LinkList.py
# @Time : 2020/9/3 22:10
# @Email: lihuacai168@gmail.com
# @Software: PyCharm
import time
def bubble(arr):
"""
>>> arr = [3,1,2,4]
>>> bubble(arr)
>>> arr == [1, 2, 3, 4]
True
"""
if len(arr) <= 1:
retu... |
from math import exp
def f(x):
return x*exp(-x)
#Numerically Integrate f(x) from 0 to 50
intgrl = 0.0
x = 0
xmax = 50
dx = 0.0001
while x<xmax:
intgrl += dx*f(x)
x += dx
print("Integral=", intgrl, "error=", abs(1-intgrl))
# dx has to be smaller than 10**-4 to yield error 10**-10
|
#!/usr/bin/env python3
"""Flip Me Over"""
def matrix_transpose(matrix):
"""transpose a matrix"""
new_matrix = []
for i in range(len(matrix[0])):
new_row = []
for j in range(len(matrix)):
new_row.append(matrix[j][i])
new_matrix.append(new_row)
return new_matrix
|
from utils import enumerate_combinations as ec
import unittest
import sys
sys.path.append('..')
class TestFunction(unittest.TestCase):
"""
Test utils.enumerate_combinations
"""
def setUp(self):
self.lst = [1, 2]
def test(self):
expected_result3 = set()
expected_result2... |
# cook your dish here
def minutes_converter(time,spell):
t=time.split(':')
hr=int(t[0])
minutes=int(t[1])
total_minutes=0
if hr==12:
if spell=='AM':
total_minutes=minutes
else:
total_minutes=(minutes)+12*60
else:
if spell=='AM':
total_m... |
#!/usr/bin/env python3.9
"""
Classe responsável por executar a regra de negócio RN1 para descobrir o destino
da espaçonave
RN1:O local de chegada pode ser conhecido sabendo que as vogais do nome da estrela
são atribuídas à uma sequência Fibonacci que começa em 1 e termina em 8,
onde A = 1, E = 2, I = 3, O = 5 e U = ... |
#Short Substrings
n = int(input())
for _ in range(n):
s = input()
r = s[0]
for i in range(1,len(s),2):
r = r+s[i]
print(r) |
#In Search of an Easy Problem
n = int(input())
l = input().split()
if l.count('1'):
print("HARD")
else:
print("EASY") |
### write your solution below this line ###
class Stack:
def __init__(self, size):
self.size = size
self.data = [None]* self.size
self.top = -1
def push(self,val):
if not self.isFull():
self.data.append(val)
self.top += 1
def isFull(self):
if... |
#Anton and Letters
n =[each for each in input() if each !=" " and each !="}" and each !="{" and each !=","]
print(len(set(n))) |
import pyautogui
from time import sleep
pyautogui.PAUSE = 1
sleep(5)
# this pyautogui.position() returns the x and y coordinates of the mouse
# one you start the execution of the file, you have 5 seconds to position the mouse on a point who's coordinates you need
# for example: if i place the mouse on top of ... |
from sys import argv
#open and parse file
#M,N are 2 integers: number of rows and columns
#maze is a list of strings
with open(argv[1]) as f:
M,N=map(int,(f.readline()).split())
maze=[x.strip() for x in f.readlines()]
#find left and right immediate exits, mark them with '1'
#find up and down immediate exits, ... |
num1 = float(input("Digite o primeiro numero: "))
num2 = float(input("Digite o segundo numero: "))
num3 = float(input("Digite o terceiro numero: "))
print(max(num1, num2, num3)) |
# operador igualdade == (x == y)
# operador diferente != (x != y)
# a=(100!=100) a receberá FALSE
# > operador maior que (1 > 0) retorna TRUE
# < operador menor que (1 < 0) retorna FALSE
# >= operador maior ou igual (1 >= 1) retorna TRUE
# <= operador menor ou igual (1 <= 2) retorna TRUE
'''
tste
'''
print(10*'-'... |
#Fatiando listas
#lista = [start:stop:step]
#start = indice inicial, default = 0
#stop = indice final, default = numElementosLista
#step = incremento de indice, default = 1
lista = "Bem vindo ao curso de python"
print(lista[10])
print(lista[:20])
print(lista[10:20])
print(lista[::2])
print(lista[::3])
print(lista[::-... |
num1 = float(input("Digite o primeiro numero: "))
num2 = float(input("Digite o segundo numero: "))
num3 = float(input("Digite o terceiro numero: "))
valores = [num1, num2, num3]
valores.sort(reverse=True)
for i in valores:
print(i)
|
a = 25.4
if(float(a).is_integer()):
print("O numero e inteiro!")
else:
print("O numero nao e inteiro!") |
i = 0
while (i < 1):
print("Estou em loop")
if(input("Digite uma letra: ")=="q"):
break |
"""
The Game of Life is a cellular automaton devised by the British mathematician John Horton Conway in 1970.
It is the best-known example of a cellular automaton.
Conway's game of life is described here:
A cell C is represented by a 1 when alive, or 0 when dead, in an m-by-m (or m×m) sq... |
'''
This problem finds all elements that are bigger than all elements
on its right
keep pushing the elements on the stack...
before pushing an element, check if there top of stack is smaller
than the current element
if smaller, then keep poping until you find an element bigger than
current and then push current elemen... |
'''
Move the zeros to the end,
If zeros to move to the start,
we should start from the end of the
array for efficiency
'''
def move_zero(arr):
if len(arr) < 2:
return
i = len(arr)
j = 0
start_zero = -1
while j < i:
if arr[j] != 0:
if start_zero != -1:
a... |
from copy import copy
def print_permute(input, lst, printed):
if len(input) == 1:
lst.append(input[0])
word = ''.join(lst)
if word not in printed:
printed.add(word)
print(word)
lst.pop()
else:
i = 0
while i < len(input):
newinp... |
'''
In an array, if a particular element is happenning more than
N/2 times where N is the size of the array, then that is the
majority element.
Start with the first element and mark that is majority and
set it's count at 1. If subsequent elements equal to that element,
increment count and if not equal decrement the ... |
#-------------------------------------------------------------------------------
# Author: NTalukdar
#
# Created: 30-01-2014
# Copyright: (c) NTalukdar 2014
#-------------------------------------------------------------------------------
def max_subarray(arr):
max_sofar = 0
max_ending_here = 0
fo... |
#-------------------------------------------------------------------------------
# Name: quicksort
# Purpose:
#
# Author: NTalukdar
#
# Created: 27-01-2014
# Copyright: (c) NTalukdar 2014
#-------------------------------------------------------------------------------
def quicksort(array, start, end):... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.