text stringlengths 37 1.41M |
|---|
# Given an array of integers A with even length, return true if and only if it is possible to reorder it such that A[2 * i + 1] = 2 * A[2 * i] for every 0 <= i < len(A) / 2.
#
#
#
#
#
#
#
#
#
#
#
# Example 1:
#
#
# Input: A = [3,1,3,6]
# Output: false
#
#
# Example 2:
#
#
# Input: A = [2,1,2,6]
# Output: false
#
#
# ... |
# -*- coding:utf-8 -*-
# Given a string s, return the longest palindromic substring in s.
#
#
# Example 1:
#
#
# Input: s = "babad"
# Output: "bab"
# Note: "aba" is also a valid answer.
#
#
# Example 2:
#
#
# Input: s = "cbbd"
# Output: "bb"
#
#
# Example 3:
#
#
# Input: s = "a"
# Output: "a"
#
#
# Example 4:
#
#
#... |
# Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.
#
# Note: For the purpose of this problem, we define empty string as valid palindrome.
#
# Example 1:
#
#
# Input: "A man, a plan, a canal: Panama"
# Output: true
#
#
# Example 2:
#
#
# Input: "race a c... |
# -*- coding:utf-8 -*-
# A complete binary tree is a binary tree in which every level, except possibly the last, is completely filled, and all nodes are as far left as possible.
#
# Write a data structure CBTInserter that is initialized with a complete binary tree and supports the following operations:
#
#
# CBTIn... |
# Given an array arr of 4 digits, find the latest 24-hour time that can be made using each digit exactly once.
#
# 24-hour times are formatted as "HH:MM", where HH is between 00 and 23, and MM is between 00 and 59. The earliest 24-hour time is 00:00, and the latest is 23:59.
#
# Return the latest 24-hour time in "HH:MM... |
# You are given an integer array nums and you have to return a new counts array. The counts array has the property where counts[i] is the number of smaller elements to the right of nums[i].
#
#
# Example 1:
#
#
# Input: nums = [5,2,6,1]
# Output: [2,1,1,0]
# Explanation:
# To the right of 5 there are 2 smaller elemen... |
# Given a n x n matrix where each of the rows and columns are sorted in ascending order, find the kth smallest element in the matrix.
#
#
# Note that it is the kth smallest element in the sorted order, not the kth distinct element.
#
#
# Example:
#
# matrix = [
# [ 1, 5, 9],
# [10, 11, 13],
# [12, 13, ... |
# Given the root of a binary tree, calculate the vertical order traversal of the binary tree.
#
# For each node at position (x, y), its left and right children will be at positions (x - 1, y - 1) and (x + 1, y - 1) respectively.
#
# The vertical order traversal of a binary tree is a list of non-empty reports for each u... |
"""
Lambidas são funções em nome - funções anônimas
#lambida
lambda x: 3 * x + 1
#Como utilizar a expressão lambida
calc = lambda x: 3 * x + 1
print(calc(4))
# Expressão Lambida com multiplas entradas
nome_completo = lambda nome, sobrenome: nome.strip().title() + ' ' + sobrenome.strip().title()
print(nome_comp... |
"""
raise => lança exceções
raise TipoDoError('Menssagem de Error')
"""
#Exemplo
def colore(texto, cor):
if type(texto) is not str:
raise TypeError('O Texto precisa ser uma string')
if type(cor) is not str:
raise TypeError('A cor precisa ser uma string')
print(f'O texto {texto} será ... |
"""
List Comprehension
Podemos adicionar estruturas condicionais lógicas as nossas list comprehension
"""
#Exemplo
#1
numeros = [1, 2, 3, 4, 5, 6]
pares = [numero for numero in numeros if numero % 2 == 0]
impares = [numero for numero in numeros if numero % 2 != 0]
print(numeros)
print(pares)
print(impares)
# Re... |
"""
print("Qual é Seu nome?")
nome = input()
# print('Seja Bem-Vindo(a) %s' % nome.upper())
# print('Seja Bem-Vindo(a) {0}' .format(nome.upper()))
print(f'Seja Bem-Vindo(a) {nome.title()}')
ano = input('Em que ano você nasceu ? \n')
print(f'Sua idade é {2020 - int(ano)} anos')
numero = range(1, 10)
nome = 'Franc... |
__author__ = 'ddow'
"""
Notes on creating a form letter.
Continuing from almost the same file from last week.
This time, Dan was at the computer.
"""
# We explore three ways of filling data into a form letter.
name, units, item, unitprice = 'Customer', 20, 'turtles', 40.2
total = units * unitprice
signature = 'Sarah... |
""" Dynamic programming by memoization """
def lcs_by_memoization(str1, str2, len_str1, len_str2, arr):
if arr[len_str1][len_str2] != -1:
return arr[len_str1][len_str2]
else:
if len_str1 == 0 or len_str2 == 0:
arr[len_str1][len_str2] = 0
elif str1[len_str1-1] == str2[len_str2... |
class BSTNode:
data = None
parent = None
left = None
right = None
def __init__(self, data=None):
self.data = data
class BinarySearchTree:
def __init__(self):
self.root = None
self.data_string = ""
def insert(self, data=None):
new_node = BSTN... |
"""
作者:北辰
功能:模拟掷骰子
版本:2.0
日期:05/07/2018
2.0新增功能:模拟投掷两个骰子
"""
import random
def roll_dice():
"""
模拟掷骰子
"""
roll = random.randint(1,6)
return roll
def main():
"""
主函数
"""
total_times = 10000
# 初始化次数列表
result_list = [0] * 11
# 初始化点数列表
roll_list = l... |
import random
from time import time
from sys import getsizeof
random.seed(50)
def is_prime(n):
"""
Return True if n is prime else False
"""
for i in range(2, n//2 + 1):
if n % i == 0:
return False
return True
def get_prime(start, count=1, step=1, multiplie... |
import pandas as pd
#https://archive.ics.uci.edu/ml/machine-learning-databases/mushroom/agaricus-lepiota.names
#
# TODO: Load up the mushroom dataset into dataframe 'X'
# Verify you did it properly.
# Indices shouldn't be doubled.
# Header information is on the dataset's website at the UCI ML Repo
# Check NA Encod... |
import streamlit as st
from PIL import Image
# Use this if you want a backround image
# page_bg_img = '''
# <style>
# body {
# background-image: url("https://images.unsplash.com/photo-1542281286-9e0a16bb7366");#Put the URL in the quotes
# background-size: cover;
# }
# </style>
# '''
# st.markdown(page_bg_img, unsafe_a... |
def selection_sort(list_a):
indexing_length = range(0, len(list_a)-1) # [0,1,2]
for i in indexing_length:
min_value = i # 0 # 1
for j in range(i+1, len(list_a)):
if list_a[j] < list_a[min_value]: # 7 < 6 # 0 < 7
min_value = j
if min_value != i:
... |
"""
CP1404/CP5632 - Practical
Student: Siyan Tao
Electricity_bill
Create an electricity bill estimator
"""
TARIFF_11 = 0.244618
TARIFF_31 = 0.136928
print("Electricity bill estimator 2.0")
tariff = int(input("Which tariff? 11 or 31: "))
daily_use_kwh = float(input("Enter daily use in kwh: "))
days = int(input("Enter n... |
"""
CP1404/CP5632 - Practical
Student: Siyan Tao
Shop_calculator
"""
number_of_items = int(input("Number of items: "))
total = 0
while number_of_items <= 0:
print("Invalid number of items")
number_of_items = int(input("Number of items: "))
for i in range(number_of_items):
price= float(input("Price of item: ... |
"""
CP1404 - Practical
Temperature conversions
"""
def main():
menu ="""C - Convert Celsius to Fahrenheit\nF - Convert Fahrenheit to Celsius\nQ - Quit"""
print(menu)
choice = input(">>> ").upper()
while choice != "Q":
if choice == "C":
celsius = float(input("What is your Celsius: "))... |
# 1.
# Вх: список чисел, Возвр: список чисел, где
# повторяющиеся числа урезаны до одного
# пример [0, 2, 2, 3] returns [0, 2, 3].
def rm_adj(nums):
return list(set(nums))
# 2. Вх: Два списка упорядоченных по возрастанию, Возвр: новый отсортированный объединенный список
def concat_list(list1, list2):
resul... |
#Q1 list of songs
songs = ["ROCKSTAR", "Do It", "For The Night"]
#Q2 print out 1st & 2nd items in list
print(songs[0])
print(songs[2])
#Q2 printed "Do It"and "For The Night"
print(songs[1:3])
#Q3 update the last element
songs[2] = "Treat You Better"
print(songs)
#Q4 three songs added
songs.append("The Man")
songs.... |
#Herencia Múltiple - MRO
#http://www.srikanthtechnologies.com/blog/python/mro.aspx
class A:
a = 0
def cocinando(self):
print("A está cocinando")
#[A] + merge(L[O], [O])
#[A, O]
class B:
a = 1
def cocinando(self):
print("B está cocinando")
class C(B):
a = 2
def cocinando(self):... |
AlphaNum=1
for Alpha in (" Good night !!!") :
print ("Letter ", AlphaNum, " is ", Alpha)
AlphaNum+=1 |
# use while to create a loop to calculated investment
# This program asks user to enter $ amount for priciple and add annual rate.
# To stop the program user needs to entre SENTENIAL flag which is 0
SENTENIAL = 0
years = 1
principle = float(input('What is your principle amount invested?: '))
interestRate = float... |
# Calculate area of triangle using while not and if else
# Has UX component to
goodBase = False
while not goodBase:
base = int(input ('Enter the base :'))
if base <= 0:
print ('Error - the base length must be a positive number. You entered', base)
else:
goodBase = True
goodHeight = False... |
#!/usr/bin/python
def sum_string(str):
for i in range(len(str)-2):
if int(str[i])+int(str[i+1]) == int(str[i+2]):
continue
else:
return False
return True
print sum_string("1234566324")
print sum_string("12358")
print sum_string("112358")
print sum_string("01123")
print s... |
#!/usr/bin/python
def swap(input,i,j):
input[i],input[j]=input[j],input[i]
def quick_sort(input,start,end):
if start < end:
pivot = partition(input,start,end)
quick_sort(input,start,pivot-1)
quick_sort(input,pivot+1,end)
return input
def partition(input,start,end):
pivot = star... |
class Node:
def __init__(self,value=None,next=None):
self.value = value
self.next = next
class LinkedList:
def __init__(self):
self.head = None
def add_before_head(self,node):
node.next = self.head
self.head = node
def print_list(self):
node = self.hea... |
length=6
nlength=length-1
i=1
j=1
for i in range(length):
for j in range(i):
print("X",end="")
print("")
for i in range (1,length):
for j in range(i,nlength):
print("X",end="")
print("")
|
print("Ingrese base y altura de un rectangulo, deben ser mayores a 0 en caso contrario se repetira")
while True:
base=int(input("Ingrese la base: "))
height=int(input("Ingrese la altura: "))
area=base*height
if base>0 and height>0:
break
print("El area del rectangu... |
vector1=[]
vector2=[]
print("Ingrese 5 numeros en un vector")
for i in range(1,6):
vector1.append(int(input()))
for i in range(1,12):
vector2[i]=i*2
print("",vector2[i])
|
genero=input("Ingrese su genero: ")
if genero=="Femenino" or genero=="Masculino":
if genero=="Femenino":
print("El genero ingresado es femenino")
else:
print("El genero ingresado no es valido")
|
num1=int(input("Ingrese 1 numero: "))
num2=int(input("Ingrese 2 numero: "))
num3=int(input("Ingrese 3 numero: "))
if num1<num2 and num1<num3:
if num2<num3:
print("",num1,"",num2,"",num3)
else:
print("",num1,"",num3,"",num2)
else:
if num2<num3 and num2<num1:
if num3<num1:
... |
class Asiento:
def __init__(self):
self.color = "negro"
class Auto:
def __init__(self, marca):
self.asientos = [
Asiento(),
Asiento(),
Asiento(),
Asiento()
]
mi_auto = Auto("Volskwagen")
print(mi_auto.asientos[1].color)
mi_deportivo = Au... |
#escribir una funcion que devuelva true si una palabra es palindroma
# Metodo 1
palabra = input()
palabra_invertida = palabra[::-1]
if(palabra == palabra_invertida):
print("Es palindroma")
else:
print("Noes palindroma")
|
def largest_prime(num):
ans, div = num, 1
while div < ans**(1/2.0):
if ans % div == 0:
ans /= div
div += 1
return ans
num = 600851475143
print(int(largest_prime(num)))
|
#ex:3.33
#a
string=str(input('Enter the string:'))
def reverse_string(string):
print(string[::-1])
return
reverse_string(string)
#b
string=str(input('Enter the string:'))
reverse_string(string) |
#ex:3.8
from math import pi
def perimeter(r):
result=2*pi*r
print(result)
return
perimeter(1) |
#ex:2.27
n=int(input('enter the positive number:'))
for i in range(0,4):
result=n*i
print(result)
|
from math import sqrt
def fast_prime(limit):
"""Possibly due to the overhead of iterating a list, this method is much
much faster at finding primes than the list methods I've been using before"""
# Millionth Prime in 216.03 seconds
def isPrime(n):
if (n == 1): return False
elif (n < 4): retu... |
# Designer Door Mat
# Enter your code here. Read input from STDIN. Print output to STDOUT
N,M = map(int,input().split())
c = ".|."
for i in range(N//2):
print((c*((i*2)+1)).center(M, '-'))
print(('WELCOME'.center(M,'-')))
for j in range(N//2):
print((c*((N-(j*2))-2)).center(M, '-'))
|
import math;
# сигма по нулю
taylorSin = lambda x, n: \
(((-1) ** (n) * x ** (2 * n + 1))) / math.factorial(2 * n + 1);
# сигма по нулю
taylorCos = lambda x, n: \
(((-1) ** (n) * x ** (2 * n))) / math.factorial(2 * n);
# сигма по нулю
taylorAtan = lambda x, n: \
(((-1) ** (n) * x ** (2 * n + 1))) / (2 * ... |
distancia = float(input('Qual a distancia total da viagem? '))
print('Voce esta prestes a comecar uma viagem de {:.2f} km'.format(distancia))
'''if distancia <=200:
preco = distancia*0.50
else:
preco = distancia*0.45'''
preco = distancia * 0.50 if distancia <=200 else distancia * 0.45
print('E o preco da sua p... |
n = int(input('digite um numero: '))
a = n-1
s = n+1
print('analisando o numero {}, seu antecessor e {} e seu sucessor e {}'.format(n ,a , s))
|
print('-=-'*20)
print(' Vamos analisar um triangulo?')
print('-=-'*20)
r1 = float(input('Digite um seguimento de reta: '))
r2 = float(input('Digite outro seguimento de reta:'))
r3 = float(input('Digite o terceiro seguimento de reta:'))
if r1 < r2+r3 and r2 < r1+r3 and r3 < r1+r2:
print(' Os tres seguimen... |
celcius = float(input('qual a temperatura em graus celcius:'))
kelvin = celcius + 273.15
farenheit = ((celcius*9)/5)+32
print('a temperatura de {:.2f}graus celcius corresponde a {:.2f} graus farenheit e a {:.2f} graus kelvin'.format(celcius, farenheit, kelvin))
|
p = float(input('qual e o preco do produto? R$: '))
porc = p*0.95
print('o produto de R${:.2f} com 5% de desconto ira custar : R$ {:.2f}'.format(p, porc))
|
def fatorial(n, show=False):
"""
-> Calcula o fatorial de um número informado.
:param n: O número a ser calculado.
:param show: Mostra ou não a conta do fatorial.
:return:Valor fatorial do número solicitado.
"""
f = 1
for c in range(n, 0, -1):
if show:
print(c, en... |
import random
import numpy as np
def matrix(m,n):
lst = [[random.randint(1,10) for e in range(n)]for e in range(m)]
return lst
def get_flat_list(lst,m,n):
new_lst =[]
for i in range(m):
if i %2 != 0:
reversed(lst[i])
new_lst += lst[i]
return new_lst
m = int(input("Nhập số... |
import random
while True:
current_number = 1
if random.randint(0, 1) == 0:
current_player = "human"
else:
current_player = "computer"
while current_number <= 21:
print("The current number is " + str(current_number) + ".")
print()
if current_player == "human"... |
import turtle
import random as r
t = turtle.Turtle()
t.hideturtle()
t.penup()
t.goto(0, -200)
t.speed(10)
t.pensize(10)
t.pencolor("black")
t.pendown()
t.circle(200)
t.penup()
t.speed(10)
t.shape("turtle")
t.pencolor('green')
t.goto(0, 0)
angle = r.randint(0, 360)
t.right(angle)
t.showturtle()
count = 0
while True:
... |
a= int(input("Nhập số đảo ngược:"))
while a != 0:
print(a%10, end="")
a=a // 10
|
import turtle
t= turtle.Turtle()
def draw_polygon(a,b):
# a là số cạnh của đa giác
# b là cd các cạnh
c = 180 - (1 - 2/a)*180
for x in range(a):
t.fd(b)
t.rt(c)
turtle.done()
a = int(input("Nhập số cạnh đa giác:"))
b = float(input("Nhập độ dài cạnh:"))
draw_polygon(a,b)
|
import turtle
import random
t = turtle.Turtle()
t.shape("turtle")
t.hideturtle()
t.pensize(3)
t.color("blue")
t.speed(1)
t.penup()
t.goto(-400, 0)
t.showturtle()
dem = 0
while dem < 10:
# sinh hai giá trị ngẫu nhiên
down = random.randint(20, 50)
up = random.randint(20, 50)
t.pendown()
'''rùa tiến về... |
class Car():
x=5
n=10
def _init_(self,n,m):
self.n=n
self.m=m
def hai(self):
print("this is car")
def hello(self,colour):
print("this is color",colour)
def view(self,colour,number):
print("this is number",number,colour)
w=Car(7,8)
print(w.n)
p=Car()
p.hai()
p.hello("red")
p.view("... |
a,num = [int(x) for x in input().split()]
lista = []
for i in range(a):
x = input()
lista.append(x)
lista.sort()
print(lista[num-1]) |
import helpers
def get_available_players(players, my_drafted_players, other_drafted_players, printon):
"""
Prints a list of undrafted players by their index in players.values()
"""
available_players = []
for i in range(len(players)):
player = players.values()[i]
if 'Untracked' no... |
'''
TRANSPOSE AND FLATTEN
'''
import numpy
'''
The for loop in list comprehension just runs n (number of rows) times because we take the
input for each row in separate lines (counting for the number of rows or loops iterations)
instead of all the elements in one single line in which case the number of times the loop
r... |
'''
TEXT WRAP
'''
import textwrap
def wrap(string, max_width):
return textwrap.fill(string, max_width)
'''
textwrap.wrap(text[, width[, ...]])
Wraps the single paragraph in text (a string) so every line is at most width characters long. Returns a list of output lines,
without final newlines.
See the TextWrappe... |
# -*- coding: utf-8 -*-
"""
Created on Sat Sep 5 20:13:26 2020
@author: satwika
"""
A=10
print(A)
print?
print("Anne Satwika Teli")
print("Anne","Satwika","Teli",sep='==',end=".....")
print("Anne","Satwika","Teli",sep='==')
help(print)
help("operators")
!python --version
!pip list
a="anne"
b=10
c=30.33
type(a)
t... |
#!/usr/local/bin/python2.7
import random
def play_game(num):
while True:
a = int(raw_input("please input a number:"))
if a > num:
print "The number is bigger"
elif a < num:
print "The number is zsmaller"
else:
print "You are right!"
... |
x=input().replace("\r","")
y=input().replace("\r","")
z=input().replace("\r","")
theList=[]
theList=x.split(",")
print(x.find(y)!=-1)
print(x.find(y))
print(theList)
print(theList[0]+"--"+theList[1])
print(theList[0]==y)
print(theList[-1]==y)
print(x.upper())
print(x.title())
print(y.isnumeric())
print(x.replace(y,z)) |
import search
def getPOS(sent, dex):
ar = search.toArray(sent,' ')
if 'ing' in ar[dex] or 'ed' in ar[dex]:
return "verb"
if dex < len(sent)-1 and 'ing' in ar[dex+1] or 'ed' in ar[dex+1]:
return "noun"
return "adj"
|
#!/usr/bin/env python
import sys
s = sys.stdin.readlines()
i = 0
reverse = []
while i < len(s):
characters = s[i].rstrip()
reverse.append(characters)
i = i + 1
j = 0
while j < len(reverse):
print reverse[len(reverse) - j - 1]
j = j + 1
|
#!/usr/bin/env python3
import sys
def caps(words):
i = 0
while i < len(words):
i = 0
while i < len(words):
words[i] = words[i][:: - 1]
words[i] = words[i].capitalize()
words[i] = words[i][:: - 1]
i += 1
return words
def main():
for line in s... |
#!/usr/bin/env python
class Account(object):
# A class variable
irate = 10.0
def __init__(self, name, balance=0):
self.name = name
self.balance = balance
# self.irate = 2.0
def apply_interest(self):
self.balance += self.balance * self.irate / 100
... |
#!/usr/bin/env python
total = 0
s = raw_input()
while s != "0":
total = total + int(s)
s = raw_input()
print total
|
#!/usr/bin/env python3
import sys
def main():
s = sys.argv[1]
ls = list(s)
i = 1
while i < len(ls):
ls[i - 1], ls[i] = ls[i], ls[i - 1]
i += 2
print(''.join(ls)
if __name__ == '__main__':
main()
|
#!/usr/bin/env python
import sys
word = sys.argv[1]
i = 0
while i < len(word) - 1:
print(word[i] + word[i +1])
i += 1
|
#!/usr/bin/env python3
import sys
def anagram(a, b):
for c in a:
if c not in b:
return False
b = b.replace(c, '', 1)
return True
def main():
a, b = sys.stdin.readline().strip().split()
print(anagram(a, b))
if __name__ == '__main__':
main()
|
#!/usr/bin/env python3
def sumup(list_of_numbers):
#base case
if list_of_numbers == []:
return 0
return list_of_numbers[0] + sumup(list_of_numbers[1:])
x = sumup([5, 3, 1, 3])
print(x)
|
#!/usr/bin/env python
new = 0
old = 0
i = 0
while i < 6:
n = input()
n = old
if old < new:
old = new
print "lower"
if old > new:
old = new
print "higher"
if new < old:
print "lower"
if new > old:
print "higher"
else:
old = new
prin... |
person = {
'name': 'ricky',
'lastN': 'medina',
'age': 3
}
print(person['name'], person['age'])
print('Hello %(name)s. You have %(age)d years old' %person)
print('height' in person) # check for key existance
print('age' in person)
|
"""
This problem was asked by Google.
Given an array of strictly the characters 'R', 'G', and 'B',
segregate the values of the array so that all the Rs come first,
the Gs come second, and the Bs come last.
You can only swap elements of the array.
Do this in linear time and in-place.
For example, given the array ['G'... |
"""
This problem was asked by Airbnb.
Given a list of integers,
write a function that returns the largest sum of non-adjacent numbers.
Numbers can be 0 or negative.
For example, [2, 4, 6, 2, 5] should return 13, since we pick 2, 6, and 5.
[5, 1, 1, 5] should return 10, since we pick 5 and 5.
Follow-up: Can you do th... |
"""
This problem was asked by Microsoft.
Given a dictionary of words and a string made up of those words (no spaces),
return the original sentence in a list.
If there is more than one possible reconstruction, return any of them.
If there is no possible reconstruction, then return null.
For example, given the set of w... |
"""
This problem was asked by Facebook.
Given a function that generates perfectly random numbers
between 1 and k (inclusive), where k is an input,
write a function that shuffles a deck of cards represented
as an array using only swaps.
It should run in O(N) time.
Hint: Make sure each one of the 52! permutations of t... |
"""
This problem was asked by Uber.
Given an array of integers,
return a new array such that
each element at index i of the new array
is the product of all the numbers in the original array except the one at i.
For example, if our input was [1, 2, 3, 4, 5],
the expected output would be [120, 60, 40, 30, 24].
If our i... |
"""
This problem was asked by Facebook.
A builder is looking to build a row of N houses
that can be of K different colors.
He has a goal of minimizing cost
while ensuring that no two neighboring houses are of the same color.
Given an N by K matrix where the nth row and kth column represents the cost
to build the nth ... |
"""
This problem was asked by Twitter.
Implement an autocomplete system.
That is, given a query string s and a set of all possible query strings,
return all strings in the set that s as a prefix.
For example,
given the query string de and the set of strings [door, deer, deal],
return [deer, deal].
Hint: Try preproce... |
class Usuario():
def __init__(self, nome, endereco, email, telefone, id):
self.nome = nome
self.endereco = endereco
self.email = email
self.telefone = telefone
self.id = id
class Livro():
def __init__(self, titulo, autor, publicacao, id, area, categoria):
self.t... |
def cria_frase( palavras):
return ' '.join(palavras)
palavra=True
frase=[]
while palavra:
palavra= input('Digite algo, pressione <Enter para sair>' )
frase.append(palavra)
print(cria_frase(frase))
|
class State:
def __init__(self, state, parent, cost, move, key):
super().__init__()
self.state = state
self.parent = parent
self.cost = cost
self.move = move
self.key = key
if self.state:
self.to_string = ''.join(str(ch)+"," for ch in self.state)... |
import subprocess
def get_strings_with_offset(file_path):
""" Obtains strings from a file
Arguments:
file_path -- path from the binary to get strings from
Returns:
strings_with_offset -- strings found. The first word of each string is the offset
on the file
"""
#EXECUTE STRING... |
str0 = 'BWWWWWBWWWW'
def EnRunLength(str0):
code = ''
connect = 1
for i in range(1, len(str0)):
if str0[i] != str0[i-1]:
code = code + str(connect) + str0[i-1]
connect = 1
else:
connect += 1
code = code + str(connect) + str0[len(str0) - 1]
retu... |
# Question 1
import csv
file = 'student.csv'
# Reading
def readData():
print("Student First Name \t Student Last Name \t Grade")
with open(file, 'r') as my_file:
reader = csv.reader(my_file)
sum_csv = 0
count = 0
for row in reader:
print("\t\t\t\t".join(row))
... |
#!/usr/bin/env python
import random
var = random.randint(1,100000)
print(" Welcom to Number Guessing Game ")
while 1:
test= input('Enter a Integer Number of your wish : ')
if var == test:
print( "You've guessed the correct number")
break
elif var < test:
print( "Your guess is greater then the number")
els... |
# Faça um programa, com uma função que necessite de um argumento. A função retorna o valor de caractere ‘P’,
# se seu argumento for positivo, ‘N’, se seu argumento for negativo e ‘0’ se for 0.
def funcao(arg1):
if arg1 > 0:
return 'P'
elif arg1 == 0:
return 0
else:
return 'N'
num... |
#DESAFIO - Data com mês por extenso.
# Construa uma função que receba uma data no formato DD/MM/AAAA e devolva uma string no formato D de mesPorExtenso de AAAA.
# Opcionalmente, valide a data e retorne NULL caso a data seja inválida.
# Considere que Fevereiro tem 28 dias e que a cada 4 anos temos ano bisexto, sendo... |
"""
CS50 AI with Python: Search
LECTURE 0:
agent: entity that perceives its environment and acts upon that environment.
state: configuration of the agent in its environment.
initial state: state in which the agent begins. Starting point for search algorithm.
actions: choices that can be made in any given state.
Actio... |
# 예제 5-4 : 재귀 함수 종료 예제
def recursive_function(i):
# 재귀함수 시작 부분에 100번째 출력했을 때 종료되도록 종료 조건 명시
# 의도적으로 무한루프를 이용하는 것이 아니라면, 반드시 종료조건을 통해 언젠가는 프로그램이 정해진 값을 반환하도록 !
if i == 100:
return
# 종료조건 : 100번째 재귀함수 <- 더 이상 함수가 호출되지 않고 종료
# 이후 차례대로 99번째 재귀함수부터 종료되어 결과적으로 1번째 재귀함수까지 종료 -> 스택에 데이터를 넣었다가 빼는 형태... |
# 예제 11-1 : 소수의 판별 - 기본적인 알고리즘
# 소수 판별 함수
def is_prime_number(x): # 특정 자연수 x가 소수의 정의를 만족하는지 여뷰를 반복문을 이용하여 하나씩 확인
# 2부터 (x - 1)까지의 모든 수를 확인하며
for i in range(2, x):
# x가 해당 수로 나누어 떨어진다면
if x % i == 0: # 입력으로 주어진 수 x가 i로 나누어 떨어지는 경우가 하나라도 존재한다면
return False # 소수가 아님
return Tr... |
# 실전문제 7-8 : 떡볶이 떡 만들기
def max_height(n, m, h_list):
height = 1
while height >= 1:
result = 0
for i in range(n):
if h_list[i] > height:
result += h_list[i] - height
else:
continue
if result == m:
return height
... |
#time Complexit O(n*k) n is the no of elements in array and s is the length of the string
class Solution(object):
def groupAnagrams(self, strs):
primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101]
d = {}
if not strs:
retu... |
# menu_text.py
#
# simple python menu
# https://stackoverflow.com/questions/19964603/creating-a-menu-in-python
#
city_menu = { '1': 'Chicago',
'2': 'New York',
'3': 'Washington',
'x': 'Exit'}
month_menu = {'0': 'All',
'1': 'January',
'2': 'February... |
#https://stackoverflow.com/questions/35166633/how-do-i-multiply-each-element-in-a-list-by-a-number/35166717
width = input("Width of multiplication table: ")
height = input ("Height of multiplication table: ")
w=(int(width)+1)
h=int(height)
t = "X"
b=list(range(0,w))
a=range(0,h)
for j in a:
meg=""
j+=1
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.