text stringlengths 37 1.41M |
|---|
def main():
with open("input.txt", "r+") as file:
content = file.readlines()
valid_password_count = 0
for item in content:
parameters = item.split(' ')
range = parameters[0]
index1 = int(range.split('-')[0])-1
index2 = int(range.split('-')[1... |
# -*- coding: utf-8 -*-
"""
Created on Wed Apr 10 06:33:58 2019
@author: Hari Chukkala
"""
# Description of the Problem:
#You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers... |
# -*- coding: utf-8 -*-
"""
Created on Tue Sep 20 19:55:52 2016
@author: Vivek
"""
# Some string gotchas
# define the strings
str1 = 'hello'
str2 = ','
str3 = 'world'
str4 = str1+str3
# do stuff with it
# 1) repeat something 3 times
str3 * 3
# worldworldworld
# 2) substring only 'el' in 'hello'
str1[1:3]
# el
#... |
# Ingresar palabras desde el teclado hasta ingresar la palabra FIN. Imprimir aquellas que empiecen y terminen con la misma letra.
cadena = input('palabra: ')
while cadena != 'FIN':
if len(cadena) > 0 and cadena.endswith(cadena[0]):
print(cadena)
cadena = input('palabra: ') |
tablero = [
'-*-*-',
'--*--',
'----*',
'*----'
]
# retorna un nuevo string con la casilla incrementada
def renovar_string(a_modificar, pos, value):
"""Recibe un string y remplaza el caracter en pos por value.
Parametros:
a_modificar : str
El string que se va a ... |
# Modificar el código previa para que se imprima la cadena “TIENE R” si la palabra contiene la letra r y sino, imprima “NO TIENE R”.
for i in range(4):
cadena = input('cadena: ')
if 'r' in cadena:
print('TIENE R')
else:
print('NO TIENE R')
|
# Escribir un programa que ingrese 4 palabras desde el teclado e imprima aquellas que contienen la letra “r”
for i in range(4):
cadena = input('cadena: ')
if 'r' in cadena:
print(f'cadena que contiene una \'r\': {cadena}')
|
"""
12.03.2019, Salı, Ankara, Türkiye
Python Yazı & Tura Oyunu
Orçun Madran - madran.net
"""
from random import randint
yazi = 0
tura = 0
kere = int(input("Kaç kere? "))
for x in range(kere):
gelen = randint(0,1)
if gelen == 0:
yazi += 1
else:
tura +=1
print(str(x+1) + ". ... |
# more strings and text
# defining x as "theyre are %d types of people, which calls a number (the %d)
x = "there are %d types of people." % 10
# defining binary as "binary"
binary = "binary"
# defining doNot as "don't"
doNot = "don't"
# defining y as "those who know %s and those who know %s", the %s will call somethin... |
"""
algorithms.py:
Contains the PathfindingAlgorithms class which contains various path finding functions.
CSC111 Final Project by Tony He, Austin Blackman, Ifaz Alam
"""
from queue import PriorityQueue
import pygame
from matrix_graph import MatrixGraph
from clock import Timer
class PathfindingAlgorithms:
"""
... |
'''
Problem 9:
A Pythagorean triplet is a set of three natural numbers, a < b < c, for which,
a^2 + b^2 = c^2
For example, 3^2 + 4^2 = 9 + 16 = 25 = 52.
There exists exactly one Pythagorean triplet for which a + b + c = 1000.
Find the product abc.
'''
import math
def solve():
answer = 1
numInput = 1000
... |
"""Maintaining overall state
"""
import sys
import pygame
from alphabet import Alphabet
from ledboard import Ledboard
#from pygame.locals import *
class Timetable():
"""Class to maintain the state of the timetable
"""
def __init__(self, rows, columns):
"""Timetable contains representation of the ... |
# Gelin Eguinosa Rosique
import time
class TimeKeeper:
"""
Class to keep track of the time the programs expends processing the
information. It doesn't count the time the program expends waiting for input
from the user.
"""
def __init__(self):
"""
Create the basic variables to... |
from urllib2 import urlopen
from BeautifulSoup import BeautifulSoup
url = "https://en.wikipedia.org/wiki/Game_of_Thrones#cite_note-S1avgS2ratings-276"
response = urlopen(url).read()
wiki = BeautifulSoup(response)
viewer_numbers_file = open("viewer_numbers.csv", "w")
viewer_numbers_file.write("The number of viewers of... |
"""Implements class DecisionTreeclassifier, to
- hold input data (attributes, classes),
- fit a binary decision tree to efficiently decide a predicted class
for an input row of data
- make predictions
Attributes:
rows
colnames (not currently used)
tree (added by fit() method)
Methods:
fit()
predict()
Major helper... |
"""This file contains the Phonebook functionality."""
import os
class Phonebook():
"""Phonebook Class."""
def __init__(self, cachedir):
"""The constructor for the Phonebook class."""
self.entries = {}
self.filename = "phonebook.txt"
self.file_cache = open(os.path.join(str(cache... |
# Simple function demo
# check for prime number
def is_prime(number):
divider = 2
while divider < number / 2: # bis zur Hälfte
if number % divider == 0:
# Zahl lässt sich ohne Rest teilen
return False
divider = divider + 1
return True
i = 2
while i < 100:
if is_... |
import multiprocessing as mp
import traceback
import random
import time
# This routine is actually the routine that is parallelized. All parallel
# processes do nothing but run this routine. Everything else is handled by
# the handler and the main.
def myWorker(input_queue, output_queue, start_time):
# Thi... |
#!/usr/bin/python
from Employee import Employee
def main():
name = raw_input("What's your name? ")
age = raw_input("What's your age? ")
position = raw_input("What is your position? ")
e = Employee()
e.create(name,age,position)
if __name__ == "__main__":
main() |
#Creadting and writing a file
fw = open('sample.txt', 'w')
fw.write('This file is created using a python script, Sounds Amazing. Right?\n')
fw.write('I like Bacon\n')
fw.close()
#Reading a file
fr = open('sample.txt','r')
text = fr.read()
print(text)
fr.close() |
import random
import numpy as np
import matplotlib.pyplot as plt
possible = 6
dice = 2
size = possible*dice
mean = []
frequency = []
i = 0
while(i<size):
d1 = random.randint(1,6)
d2 = random.randint(1,6)
avg = (d1+d2)/2
mean.append(avg)
# index = ((mean[i]*2)-1)
# freq... |
magicNumber = 17
# Ok this program finds a magic number
print(5+4)
#Break here
print("Kushal"+"Sharma")
print("Kushal",17)
for n in range(101):
if n is magicNumber:
print(n,"is the magic number")
break
else:
print(n)
#Continue here
numbersTaken = [2,9,13,12,17]
... |
# i = 0
def series_sum(n):
i = 0
add = 0
while(i<n):
add = add + 1/n
n = n+3
i = i+1
return add |
"""
Including some customized plot
"""
from .basic_import import *
import matplotlib
import matplotlib.pyplot as plt
def bar_plot(sizes, labels, bar_ylabel, bar_title, colors=None, with_show=False):
"""
Draw barplot with count on top
Code from https://www.kaggle.com/phunghieu/a-quick-simple-eda
"""
... |
op=float(input("Enter yesterday open price:"))
hp=float(input("Enter yesterday high price:"))
lp=float(input("Enter yesterday low price:"))
cp=float(input("Enter yesterday close price:"))
oc=float(input("Enter today open price:"))
hc=float(input("Enter today high price:"))
lc=float(input("Enter today low price:"))
cc=f... |
def insidebar(open,high,low,close,volume):
insidebarlist=[False]
for i in range(len(high)):
if i==len(high)-1:
break
elif high[i+1]<high[i] and low[i+1]>low[i]:
insidebarlist.append(True)
else:
insidebarlist.append(False)
return insidebarlist
def ... |
'''This program is used to print the length of a string'''
name=input("Enter your name:")
print("Length of your name is:",len(name)) #Printing length of entered string
'''This program is used to check if a string is palindrome or not'''
enteredstring=(input("Enter your text:")).lower()
reversedstring=""
length=len(e... |
cp=float(input("Enter today's closing price:"))
sma20=float(input("Enter 20 ma:"))
sma50=float(input("Enter 50 ma:"))
if cp>sma20 and cp>sma50:
if sma20>sma50:
print("Go long")
elif cp<sma20 and cp<sma50:
if sma20<sma50:
print("Go Short")
else:
print("Dont do anything")
|
name=input("Please enter your name:")
print("Entered Name:",name) |
pdo=float(input("Enter previous day open:"))
pdl=float(input("Enter previous day low:"))
pdh=float(input("Enter previous day high:"))
pdc=float(input("Enter previous day close:"))
P=(pdh+pdl+pdc)/3
R1=(2*P) -pdl
R2=P+(pdh-pdl)
R3=R1+(pdh-pdl)
S1=(2*P)-pdh
S2=P-(pdh-pdl)
S3=S1-(pdh-pdl)
print("Pivot:{} Resistance1:{} Re... |
from __future__ import print_function
print('hello')
x = '90'
if x == '80' :
print('test > 80')
else:
print('aaa')
for i in range(1, 10):
for j in range(1, 10):
print(i*j,end = " ")
print(end = "\n")
#list
print('==== list ====')
list = [1,2,3,4,5]
print(list)
for i in range(0, len(list)):
... |
from collections import deque
def person_is_seller(name):
'''
这里判断 被 监察人 的姓名是否以"m"结尾
'''
return name[-1] == 'm'
def dfs_search(name):
# 创建一个队列
search_queue = deque()
# 将邻居都加入到这个搜索队列中
search_queue += graph[name]
searched = []
while search_queue:
# 左边弹出,先进先出
pe... |
def merge_sort(array):
if len(array) < 2:
return array
mid = int(len(array) / 2)
# 左边
lo = merge_sort(array[:mid])
# 右边
hi = merge_sort(array[mid:])
merged_arr = []
while lo and hi:
merged_arr.append(lo.pop(0) if lo[0] <= hi[0] else hi.pop(0))
merged_arr.extend(hi ... |
def recursion(n):
"""
# fibonacci
# 递归的形式:
# f(n) = f(n-1) + f(n-2)
"""
# 1. base case/stop case
if n == 1 or n == 2:
return 1
# 2. recursive case
return recursion(n - 1) + recursion(n - 2)
"""
DFS: 深度优先搜索
BFS: 广度优先搜索
"""
import numpy as np
dim = 4
grid = [[1, 0, 1, 0... |
#!/usr/bin/python
#coding=utf-8
# a = input()
l = [ [1],[1,1] ] # 定义一个列表
for i in range(2,10): # 通过for 函数在 范围(2 , a)中取值赋值给I
# print l # 输出l 在这里不需要输出。
l.append([1,1]) # 在l 中添加一个
for j in range(1,i):
l[i].insert(j,(l[i-1][j-1]+l[i-1][j]))
for x in l:
print x
|
def binary(decimal):
if decimal==0:
return
binary(int(decimal/2))
print(decimal%2, end="")
return
def asciiBin(string):
for i in string:
binary(ord(i))
print(' ')
asciiBin('abc')
|
from copy import deepcopy
from color import *
import numpy as np
class Matrix:
n, m = 0, 0
matrix = list()
def __init__(self, n, m, list_of_lists=None):
self.n, self.m = n, m
if list_of_lists:
self.matrix = deepcopy(list_of_lists)
else:
self.matrix = np.ful... |
# -*- coding: utf-8 -*-
#Decorator的使用
#The usage of decorator in python
import functools
def log(*text):
def decorator(func):
@functools.wraps(func)
def wrapper(*args, **kw):
if text:
print 'begin call %s %s():' % (text[0], func.__name__)
rst =... |
x=float(input("x:"))
y=float(input("y:"))
print("x+y=",x+y)
print("x-y=",x-y)
print("x*y=",x*y)
print("x/y=",x/y)
print("x//y=",x//y)
print("x%y=",x%y)
print("x**y=",x**y)
print("-x=",-x)
print("-y=",-y)
print("abs(x)=",abs(x))
print("abs(y)=",abs(y))
print("abs(-x)=",abs(-x))
print("abs(-y)=",abs(-y))
|
#1.check that a string contains only a certain set of characters (in this case a-z, A-Z and 0-9)
import re
def char(string):
charRe=re.compile(r'[^a-zA-Z0-9.]')
string=charRe.search(string)
return not bool(string)
print(char("ABCabc123"))
print(char("*&%@#!"))
#2.matches a word containing 'ab'
impo... |
#1
num=int(input("enter n value:"))
a=[]
for i in range(1,num):
a.append(i)
print(a)
a.insert(3,6) #add an item to list
print(a)
a.remove(4) #delete an item in the list
print(a)
b=max(a) #largest value
print(b)
c=min(a) #smallest value
print(c)
#2
my_tuple=(1,2,3,4,5)
new_tuple=tuple(reversed(my_tup... |
#Exercise 6 in hackbright GIT curriculum
# week two, day one
#write a program that opens a file and counts how many times each space -separated wod
# occurs in that file.
# dictionary with word, counter pairs
# if word in dictionary -> increment counter
# else add word, 1 to dictionary
from sys import argv
impor... |
# 3. Реализовать функцию my_func(), которая принимает три позиционных аргумента,
# и возвращает сумму наибольших двух аргументов.
def my_func():
global arg_1, arg_2, arg_3 #теперь переменные видны не только в функции
arg_1 = int(input ('Введите число 1: '))
arg_2 = int(input ('Введите число 2: '))
arg_... |
import math
def poisson_distribution(mean, expected):
result = pow(mean, expected) * pow(math.e, -mean) / math.factorial(expected)
return result
def main():
mean = float(input())
expected = int(input())
result = poisson_distribution(mean, expected)
print("{0:.3f}".format(result))
if __name... |
import math
import sys
def nCr(n, r):
f = math.factorial
return f(n) // f(r) // f(n - r)
def binomial_distribution(boys, girls, n, m):
b_prob = boys / (boys + girls)
g_prob = girls / (boys + girls)
result = nCr(n, m) * pow(b_prob, m) * pow(g_prob, n - m)
return result
def main():
line ... |
from random import randint
def numbersgame() :
num = randint(1, 10)
print(f'\nCheet: {num}')
tries = 0
guess = int(input('\nGuess a number between 1 and 10: \nYou have 10 tries to get it right ;) '))
while guess :
diff = num - guess
if diff > 0 and tries < 9:
... |
# 2명뽑아 짝짓기 모든 경우의 수
# 입력 : 이름이 n개 들어 있는 리스트
# 출력 : 이름 2개씩 짝지을수 있는 경우의 수
def dual_name(a):
n = len(a)
for i in range(0, n-1):
for j in range(i+1,n):
print(a[i], "-", a[j])
name=["Tom","Jerry","Mike"]
dual_name(name)
|
class password:
def __init__(self, line):
self.line = line.split()
self.nums = self.line[0].split('-')
self.char = self.line[1][0]
self.password = self.line[2]
def check(self):
if (self.password[int(self.nums[0]) - 1] == self.char) \
^ (self.password[... |
import pyttsx3
import datetime
import speech_recognition as sr
import wikipedia
import webbrowser
import os
import time
system = pyttsx3.init('sapi5')
voices = system.getProperty('voices')
system.setProperty('voice', voices[1].id)
def speak(audio):
system.say(audio)
system.runAndWait()
def greetings():
h... |
'''
Print a markdown table of the top tracks by YouTube view count.
'''
import json
import sys
import datetime
def sorted_tracks(tracks):
'''
Takes a track list and sorts it by number of listens.
'''
for i, track in enumerate(tracks):
if 'listens' not in track:
tracks[i]['listens'] ... |
__author__ = 'Sanjay'
from collections import Counter
import operator
def mostTrendingBrand(numOfResponse,listOfBrands):
if numOfResponse>1:
brandCount = Counter(listOfBrands)
onlyCount = []
for ke,va in brandCount.iteritems():
onlyCount.append(va)
trendingCount = max(on... |
__author__ = 'Sanjay'
#
# Task
#
# Apply your knowledge of the .add() operation to help your friend Rupal.
#
# Rupal has a huge collection of country stamps. She decided to count the total number of distinct country stamps in her collection. She asked for your help. You pick the stamps one by one from a stack of NN co... |
__author__ = 'Sanjay'
# Task
# You are given three integers: aa, bb, and mm, respectively. Print two lines.
# The first line should print the result of pow(a,b). The second line should print the result of pow(a,b,m).
#
# Input Format
# The first line contains aa, the second line contains bb, and the third line contain... |
__author__ = 'Sanjay'
# Let's delve into one of the most basic data types in Python, the list. You are given NN numbers. Store them in a list and find the second largest number.
#
# Input Format
#
# The first line contains NN. The second line contains an array AA[] of NN integers each separated by a space.
#
# Output ... |
# Given an integer, , traverse its digits (1,2,...,n) and determine how many digits evenly divide (i.e.: count the number of times divided by each digit i has a remainder of ). Print the number of evenly divisible digits.
# Note: Each digit is considered to be unique, so each occurrence of the same evenly divisible... |
__author__ = 'Sanjay'
# from Queue import Deque
def palin(inputString):
try:
rValue = inputString[::-1]
if (inputString == rValue):
print ("It's a palindrome")
else:
print ("it's not a palidrome")
except IndexError as e:
print (e)
else:
prin... |
__author__ = 'Sanjay'
# How to create a generator in Python?
# It is fairly simple to create a generator in Python. It is as easy as defining a normal function with
# yield statement instead of a return statement.
#
# If a function contains at least one yield statement (it may contain other yield or return statements)... |
def checkPalindrome():
userInput = input("Enger a string or integer")
try:
if type(userInput) is str:
if userInput == userInput[::-1]:
print ('its a palindrome')
else:
raise Exception
else:
print ("is it something else?")
ex... |
__author__ = 'Sanjay'
#calculating a sum of list of numbers.
def sumOfList(inp):
s = 0
for i in inp:
s = s +i
print (s)
return s
#Recurssion methodology now
# three LAWS OF RECURSSION
# A recursive algorithm must have a base case.
# A recursive algorithm must change its state and move toward ... |
__author__ = 'Sanjay'
def compareTwoStrings(s1,s2):
if s1 and s2 is not '':
x = list(s1)
y = list(s2)
x.sort()
y.sort()
print (x,y)
if s1 == s2:
print("both strings are equal")
else:
print("its wrong")
else:
raise RuntimeEr... |
__author__ = 'Sanjay'
# You are given a string SS. Your task is to capitalize each word of SS.
#
# Input Format
#
# A single line of input containing the string, SS.
#
# Constraints
#
# 0<len(S)<10000<len(S)<1000
# The string consists of alphanumeric characters and spaces.
#
# Output Format
#
# Print the capitalized s... |
"""
数据库查询操作 2
"""
import pymysql
# 连接数据库 (连接自己计算机可以不写host port)
db = pymysql.connect(host="localhost",
port=3306,
user='root',
password='123456',
database='stu',
charset='utf8'
)
# 创建游标 (游标对象负... |
# Lost Without a Map! (name of problem)
# Given an array of integers, return a new array with each value doubled.
# For example:
# [1, 2, 3] --> [2, 4, 6]
# For the beginner, try to use the map method - it comes in very handy quite a lot so is a good one to know.
def maps(a): # This was my method for this proble... |
'''
Sum of Pairs
Given a list of integers and a single sum value, return the first two values (parse from the left please) in order of appearance that add up to form the sum.
sum_pairs([11, 3, 7, 5], 10)
# ^--^ 3 + 7 = 10
== [3, 7]
sum_pairs([4, 3, 2, 3, 4], 6)
# ^-----^ ... |
'''
You will be given a list of strings, a transcript of an English Shiritori match.
Your task is to find out if the game ended early, and return a list that contains every valid string until the mistake. If a list is empty return an empty list.
If one of the elements is an empty string, that is invalid and should be... |
'''
Implement the function unique_in_order which takes as argument a sequence and returns a list of items without any elements,
with the same value next to each other and preserving the original order of elements.
For example:
unique_in_order('AAAABBBCCDAABBB') == ['A', 'B', 'C', 'D', 'A', 'B']
unique_in_order('ABBCc... |
expanded_form(12) # Should return '10 + 2'
expanded_form(42) # Should return '40 + 2'
expanded_form(70304) # Should return '70000 + 300 + 4'
def expanded_form(num):
list = []
n = (len(str(num))) # Number of digits within num
while n > 0: # This loop will append each digit as a str + (n-1)*'0's UNLESS ... |
'''
There is an array with some numbers. All numbers are equal except for one. Try to find it!
find_uniq([ 1, 1, 1, 2, 1, 1 ]) == 2
find_uniq([ 0, 0, 0.55, 0, 0 ]) == 0.55
It’s guaranteed that array contains at least 3 numbers.
The tests contain some very huge arrays, so think about performance.
This is the first ka... |
'''
Write a function that when given a URL as a string, parses out just the domain name and returns it as a string. For example:
domain_name("http://github.com/carbonfive/raygun") == "github"
domain_name("http://www.zombie-bites.com") == "zombie-bites"
domain_name("https://www.cnet.com") == "cnet"
'''
# Test cases m... |
# Rewrite this in Unit Test
from caesar_cipher import caesar_cipher
import unittest
class CaesarCipher(unittest.TestCase):
def test_for_functionality1(self):
self.assertEqual(caesar_cipher("Boy! What a string!", -5), "Wjt! Rcvo v nomdib!")
def test_for_functionality2(self):
self.assertEqual(... |
def decorator(func):
def wrapper(*args, **kwargs):
print "args: ", args, " kwargs:", kwargs
func(*args, **kwargs)
return wrapper
@decorator
def f(a, b, c, platypus="Why not?", test="1"):
print a, b, c, platypus, test
# f = decorator(f)
f("Bill", "Linus", "Stieve", platypus="Homer!", te... |
from Piece import Piece
from Board import Board
from Player import Player
import numpy as np
import copy
import pickle
import random
#Game class:
#maintains 4 player objects in a structure
#when initialized, creates a board, piecelist (common to all players), players, and a turn-marker
class Game():
def __init__(... |
# Type checking and casting
x = '6'
int_x = int(x)
print(int_x)
print(type(int_x))
# Variable reassignment
x = "cat"
y = "goat"
x = "python"
print(x)
a = 5
b = 6
a = a + b
print(a)
|
import sqlite3
conn=sqlite3.connect('testing.db')
c=conn.cursor()
def create_table():
c.execute("CREATE TABLE example (language VARCHAR, level TEXT, Version REAL)")
def enter_data():
c.execute("INSERT INTO example VALUES('Python', 'Beginner', 2.7)")
c.execute("INSERT INTO example VALUES('Python', 'Interm... |
import turtle
def draw_square(some_turtle,forward1,forward2):
some_turtle.begin_fill()
for x in range(2):
some_turtle.forward(forward1)
some_turtle.right(90)
some_turtle.forward(forward2)
some_turtle.right(90)
some_turtle.end_fill()
def change_pos(some_turtle,angle,length):... |
def get_coordinates(val):
""" This function simply returns a tuple containing the coordinates of a certain value
Args:
val: a number ranging from 0 to 15
Example: the value 13 would correspond to (3,1)
"""
row_val = val // 4
col_val = val % 4
return row_val, col_val
def copy_board(source_list, target_lis... |
import time
def metodoa():
#Aqui definimos el diccionario basicamente es como un hashmap con keys y values
pertsona={'izena': 'Oskar','abizena1': 'Casquero','abizena2': 'Oyarzabal'}
#De aqui lo que sacamos es el value del key 'izena'
print(pertsona['izena'])
#Para añadir otro valor al dicciona... |
##This script takes the directory containing wav files as input, convert each of the files into text
##and save the corresponding text file in the output directory.
##python SpeechToText.py --input <input_dir_name> --output <output_dir_name>
import io
import os
import shutil
import sys
import argparse
# Imports the Go... |
from math import ceil
def par_ou_impar(x):
if x % 2 == 0:
return "par"
else:
return "ímpar"
def positivo_ou_negativo(y):
if y > 0:
return "positivo"
else:
return "negativo"
def int_ou_dec(z):
if ceil(z) == z:
return "inteiro"
else:
... |
class Point:
def __init__(self):
self.x = 0
self.y = 0
p = Point()
q = Point()
print(p)
print(q)
print()
print(p is q)
|
# Nesse programa retorna-se o número de notas que cada aluno possui
arquivo = open("notas_estudantes.dat", "r")
for x in arquivo:
lista = x.split(" ")
cont = 0
for y in range(len(lista)):
try:
int(lista[y])
cont += 1
except:
cont += 0
if cont > 6:... |
numero = int(input("Digite o número principal de sua tabuada: "))
for i in range(11):
print(str(numero) + " X " + str(i) + " = ", numero * i)
|
def aprox_de_raiz(n):
aprox = 0.5 * n
betteraprox = 0.5 * (aprox + n / aprox)
while aprox != betteraprox:
aprox = betteraprox
betteraprox = 0.5 * (aprox + n / aprox)
return betteraprox
numero = int(input("Digite um número natural para aproximação de raiz: "))
print("Raiz quadrada de", numero,"=", aprox_de... |
def count_impar(lista):
resultado = 0
for i in lista:
if i % 2 == 0:
resultado += 1
return resultado
num_elementos = int(input("Número de elemetos: "))
print()
lista = []
for i in range(num_elementos):
valor = int(input("Elementos " + str(i + 1) + ": "))
lista.append(valor)
... |
dic = {"hotel":"fleabag inn", "sir":"matey", "student":"swabbie", "boy":"matey", "madam":"proud beauty", "professor":"foul blaggart", "restaurnat":"galley", "your":"yer", "excuse":"arr", "students":"swabbies", "are":"be", "lawyer":"foul blaggart", "the":"th`", "restroom":"head", "my":"me", "hello":"avast", "is":"be", "... |
f = float(input("Graus fahrenheit: "))
print(f, "°F =", 5*(f - 32)/9, "°C")
|
periodo = input("Digite o periodo em que você estuda (M, V, N): ")
if periodo == "M" or periodo == "m":
print("Bom dia!")
elif periodo == "V" or periodo == "v":
print("Boa tarde!")
elif periodo == "N" or periodo == "n":
print("Boa noite!")
else:
print("Valor inválido!")
|
numero_clientes = int(input("Número de clientes: "))
lista_codigo = []
lista_altura = []
lista_massa = []
maior_altura = 0
menor_altura = 0
maior_massa = 0
menor_massa = 0
MaiorAlturaCode = ""
MenorAlturaCode = ""
MaiorMassaCode = ""
MenorMassaCode = ""
index = -1
for i in range(numero_clientes):
print(str((i + 1)) +... |
import turtle
pen = turtle.Pen()
wn = turtle.Screen()
tam = 20
for i in range(5):
for v in range(4):
pen.forward(tam)
pen.left(90)
tam += 20
pen.right(90)
pen.forward(10)
pen.left(90)
wn.exitonclick()
|
n1 = float(input("Digite um número: "))
n2 = float(input("Digite outro número: "))
print("Adição:", n1 + n2)
print("Subtração:", n1 - n2)
print("Multiplicação:", n1 * n2)
print("Divisão:", n1 / n2)
print("Divisão inteira:", n1 // n2)
print("Módulo:", n1 % n2)
print("Exponenciação:", n1 ** n2)
|
nota1 = float(input("1° nota: "))
nota2 = float(input("2° nota: "))
media = (nota1 + nota2) / 2
print("Nota 1:", nota1)
print("Nota 2:", nota2)
print("Média:", media)
if media > 9 and media <= 10:
print("Grau: A")
print("APROVADO!")
elif media > 7.5 and media <= 9:
print("Grau: B")
print ... |
import random
import math
numero_da_sorte = int(input("Aposte um número que se encaixe no intervalo [0; 10): "))
numero_sorteado = random.random() * 10
print("AGORA CUIDADO! ESCOLHA 1 OU 2! ISSO PODE DETERMINAR SE VC SERÁ UM VENCEDOR OU PERDEDOR!")
um_ou_dois = int(input("Digite aqui a sua escolha: "))
if u... |
import turtle
def desenhabarra(t, h):
t.left(90)
t.forward(h)
t.right(90)
t.forward(20)
t.write(str(h))
t.forward(20)
t.right(90)
t.forward(h)
t.left(90)
pen = turtle.Pen()
pen.color("red")
wn = turtle.Screen()
wn.bgcolor("black")
for i in [-10, 117, 200, 240, 16... |
"""Faça um programa para uma loja de tintas. O programa deverá pedir o tamanho em metros quadrados da área a ser pintada. Considere que a cobertura da tinta é
de 1 litro para cada 3 metrosquadrados e que a tinta é vendida em latas de 18 litros, que custam R$ 80,00.Informe ao usuário a quantidades de latas de tinta a s... |
import turtle
def desenhaquadradocolorido(t, tam):
for i in ["pink", "red", "blue", "yellow"]:
t.color(i)
t.forward(tam)
t.left(90)
pen = turtle.Pen()
pen.pensize(3)
wn = turtle.Screen()
wn.bgcolor("black")
pen.speed(0)
tamanho = 20
for i in range(40):
desenhaquadrad... |
def count(s, c):
counter = 0
for i in s:
if i == c:
counter += 1
return counter
string = input("String: ")
char = input("char: ")
print()
print("Ocorrências:", count(string, char))
|
import random, sys, os
options = ['rock','paper','scissors']
print("Let's Play Rock-Paper-Scissors")
player1 = input("Player: Enter your name: ")
player2 = "Computer"
def game():
p1_option = input("%s enter your choice: " %player1).lower()
p2_option = ''.join(random.choices(options))
print("%s entered hi... |
import numpy as np
import math
def index(human_unit):
if human_unit < 2 * 10**int(math.log10(human_unit)) :
MF = 0
elif human_unit >= 2 * 10**int(math.log10(human_unit)) and human_unit < 3 * 10**int(math.log10(human_unit)):
MF = 1
raw_data = open("kekka_9.csv", 'r')
data = np.l... |
#!/usr/bin/python3
import sys
file = open("Test.txt","w")
file_text = ""
file_finish = "1"
while file_text != file_finish:
file_text = input("Enter text: ")
if file_text == file_finish:
break
file.write(file_text)
file.write("\n")
file.close()
file = open("Test.txt","r")
file_text = file.read()
file.close
... |
"""
Solution for Algorithms #344 (Reverse String)
- Space Complexity: O(1)
- Time Complexity: O(N)
Runtime: 176 ms, faster than 45.30% of Python3 online submissions for Reverse String.
Memory Usage: 17.7 MB, less than 36.68% of Python3 online submissions for Reverse String.
"""
class Solution:
def rever... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.