text stringlengths 37 1.41M |
|---|
import random
n = int(input("Enter a number: "))
a = [[0] * n for i in range(n)]
qpos = [0]*n
# putting '.' characters in nxn cells
for i in range(n):
for j in range(n):
a[i][j] = '.'
# putting randomly n number of queens in n coloumns
# so there is one queen in every row.
# but there can be multiple queens in ... |
def gettoday(today):
'''
请按此格式输入今天的日期(2019-3-25)
'''
# today = input("请按此格式输入今天的日期(2019-3-25):")
todaylist = today.split("-")
try:
year = int(todaylist[0])
month = int(todaylist[1])
day = int(todaylist[2])
except:
print("输入的格式不正确,异常退出!!")
... |
# Shirt Count and Shirt Register
shirt_count = 0
shirt_size = ""
small = 0
medium = 0
large = 0
small_size_price = 6
medium_size_price = 7
large_size_price = 8
total_small_price = 0
total_medium_price = 0
total_large_price = 0
total_price = 0
while True:
shirt_size = input("Enter the size of shirt (S,... |
# Weekday Function - Date Time Formatting
# [ ] Complete the function `weekday` to return the weekday name of `some_date`
# Use the function to find the weekday on which you were born
from datetime import date
def weekday(some_date):
formatted_string = some_date.strftime("%A")
return formatted_strin... |
# [ ] review the code, run, fix the error
tickets = int(input("enter tickets remaining (0 to quit): "))
while tickets > 0:
# if tickets are multiple of 3 then "winner"
if int(tickets/3) == tickets/3:
print("you win!")
break
else:
print("sorry, not a winner.")
ticke... |
# find and display the index of all the letter i's in code_tip
code_tip = "code a conditional decision like you would say it"
location = code_tip.find("i")
while location >= 0:
print(location)
location = code_tip.find("i", location + 1)
|
# Assigning a datetime object
from datetime import datetime
# July 4th 2022, at 4:30 PM
# Method 1
dt = datetime(2022, 7, 4, 16, 30)
print("Method 1: ", dt)
# Method 2
dt = datetime(day = 4, month = 7, year = 2022, minute = 30, hour = 16)
print("Method 2: ", dt)
# Getting a datetime attribute
fr... |
# Combining separate date and time objects into a datetime object
from datetime import datetime, time, date
# assign a time object
t = time(hour = 6, minute = 45, second = 0)
# assign a date object
d = date.today()
# combine t and d into a datetime object
dt = datetime.combine(date = d, time = t)
prin... |
# Read Write Append to a File
# Location: C:\Users\N\PycharmProjects\Python Fundamentals
# Instead of .txt, .doc or .xls file can be also created in the same way
# Create a local log file
log_file = open('log-file.txt', 'w')
# log_file = open('log-file.doc', 'w')
# log_file = open('log-file.xls', 'w')
log_fi... |
# Find out if you are closer to the current year's June or December solstice
from datetime import datetime, timedelta
import math
now = datetime.today()
december_solstice = datetime(month = 12, day = 21, year = now.year)
june_solstice = datetime(month = 6, day = 21, year = now.year)
time_to_jun = june_solstice - ... |
# [ ] using range(start,stop) - print the 3rd, 4th and 5th words in spell_list
# output should include "February", "November", "Annual"
spell_list = ["Tuesday", "Wednesday", "February", "November", "Annual", "Calendar", "Solstice"]
for item in range(2, 5):
print(spell_list[item])
# [ ] using code find the in... |
# Practice Task 4E: Birthday days
# Write a program to display a list of all your birthdays from the day you were born till 2025.
# You should also show the weekdays so you can see which of them was (or will be) on a weekend
from datetime import datetime
for yr in range(1985, 2026):
birthday = datetime(month =... |
# Program: Words after "G"/"g"
# prints all of the words that start with h-z
quote = input("Enter a famous quote: ")
quote = quote + " "
word = ""
start = 0
space_index = quote.find(" ")
while space_index >= 0:
for letter in quote[start:space_index]:
word += letter
if word[0].lower() > "g":
... |
# Cash Register Input
purchase_amounts = []
item_price = input('Enter price of items or "done" to exit: ')
while True:
if item_price.lower() == "done":
break
else:
purchase_amounts.append(item_price)
item_price = input('Enter price of items or "done" to exit: ')
print(purchase_a... |
# Pick a candy
# In this exercise, you will write a program to randomly select a candy from a box.
# [ ] Complete the function `pick_candy` so it returns a candy from box at random
from random import choice
def pick_candy():
box = ["Taffy", "Brownie", "Cookie", "Candy bar", "Chocolate", "Lollipop", "Ginger... |
# Path Operations - Check if Absolute Path, If File or Path, If file exists
import os
os.chdir('parent_dir')
print("Current working directory", os.getcwd())
abs_path = os.path.abspath('child1_dir/leaf1.txt')
print("Absolute path to leaf1.txt is: ", abs_path)
# Test if the path exists
if os.path.exists(abs_path):... |
# City Initials
!curl https://raw.githubusercontent.com/MicrosoftLearning/intropython/master/cities -o cities.txt
cities_file = open('cities.txt', "r")
cities = cities_file.read()
initials = ""
for letter in cities:
if letter.isupper():
initials += letter
elif letter == "\n":
initials +... |
"""Channels a stream of tweets matching a given term or terms to a JSON file.
Usage: python3 stream.py term1 term2 ... termN [prefix]
The output file will be [prefix].json
Note: the term arguments should be put in quotes to deal with hashtags
"""
from twitter import *
from http.client import IncompleteRead
import sys
... |
num1 = int(input('Digite o primeiro número inteiro: '))
num2 = int(input('Digite o segundo número inteiro: '))
if num1 > num2:
print('O número {} é maior que o número {}'.format(num1, num2))
elif num1 < num2:
print('O número {} é maior que o número {}'.format(num2, num1))
else:
print('Ambos os números são i... |
from datetime import date
ano = date.today().year
print(ano)
num = 5 % 2
num2 = 9 % 2
num3 = 4 % 2
num4 = 1 % 2
num5 = 4 % 2
print(num, num2, num3, num4, num5)
from random import randint
num6 = randint(1, 6)
res = num // 2
res2 = 5 // 2
print(res2)
print(res)
texto = ('Tres Pratos de Trigo para Tigres Tristes')... |
salario = float(input('Qual é o salário do funcionário? '))
if salario > 1250:
print('O reajuste é de R$ {}. Sendo assim o salário do funcionário passa a ser R$ {}'.format((salario * 0.10), (
(salario * 0.10) + salario)))
else:
print('O reajuste é de R$ {}. Sendo assim o salário do funcionário p... |
import math
peso = float(input('Digite o peso: '))
altura = float(input('Digite a altura: '))
alturaAoQuadrado = float(pow(altura,2))
imc = peso/alturaAoQuadrado
if imc <= 18.5:
print('Abaixo do peso')
elif imc >= 18.6 and imc <= 25:
print('Peso ideal')
elif imc >= 25.1 and imc <= 30:
print('Sobrepeso')
el... |
num1 = float(input('Digite um número: '))
num2 = float(input('Digite outro número: '))
num3 = float(input('Digite mais um número: '))
if num1 > num2 and num1 > num3:
if num2 < num3:
print('O maior número digitado é o {} e o menor é o {}'.format(num1, num2))
else:
print('O maior número digitado ... |
velocidadeCarro = float(input('Digite a velocidade do carro: '))
multa = float(velocidadeCarro - 80) * 7
if velocidadeCarro > 80:
print('O carro está acima do limite de velocidade!!!')
print('A multa por essa negligência é R$ {}'.format(multa))
else:
print('O carro está dentro do limite permitido de veloci... |
nota1 = float(input('Digite a primeira nota do aluno: '))
nota2 = float(input('Digite a segunda nota do aluno: '))
media = float((nota1+nota2)/2)
if media<5 and media > 0:
print('Aluno reprovado! :(')
elif media >=5 and media <= 6.9:
print('O aluno está de recuperação.')
elif media >= 7 and media <= 10:
pr... |
# coding: utf-8
# Começando com os imports
import csv
import matplotlib.pyplot as plt
from datetime import datetime
# Vamos ler os dados como uma lista
print("Lendo o documento...")
with open("chicago.csv", "r") as file_read:
reader = csv.reader(file_read)
data_list = list(reader)
print("Ok!")
# Vamos verifi... |
# PLEASE NOTE: This snippet is about basic arithmetic and variable operations
### AUFGABE: Wie funktionieren Variablenzuweisungen und Operationen mit Variablen?
# ONE Arithmetic operations with numbers
a = 10
b = 2
c = 12.7
#print(a + b)
#print(a - c)
#print(a * b)
#print(a / c)
# TWO Same artihmetic operations poss... |
"""
This file contains functions that are used to augment a cluster
"""
from collections import defaultdict
from matplotlib import pyplot as plt
from matplotlib.lines import Line2D
def flatten(list):
"""
flattens a list of lists or tuple of tuples to a 1d list
"""
return [item for sublist in list for ... |
def bubblesort(lst):
while True: # we are going to loop through the list till we get an iteration without any swap
swap = False
for y in range(0, len(lst) - 1): # In this inner loop, we are going to compare two elements next to each other (from the beginning)
... |
s = input("Bвeдитe строку:\n")
s = s.upper()
k = 0
for i in range(0, len(s)):
if s.count(s[i]) > k:
k = s.count(s[i])
print(k)
|
word = list(input())
while len(word) != 1 and len(word) != 2:
word.pop(0)
word.pop(-1)
print(''.join(word))
|
text = input()
cyrillic = 'абвгдеёжзийклмнопрстуфхцчшщъыьэюяАБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ'
latin = 'a|b|v|g|d|e|e|zh|z|i|i|k|l|m|n|o|p|r|s|t|u|f|kh|tc|ch|sh|shch||y||e|iu|ia|A|B|V|G|D|E|E|Zh|Z|I|I|K|L|M|N|O|P|R|S|T|U|F|Kh|Tc|Ch|Sh|Shch||Y||E|Iu|Ia'.split('|')
print(text.translate({ord(k):v for k,v in zip(cyrill... |
# -*- coding: utf-8 -*-
import sqlite3
db_file="db_chattrain.db"
def create_connection():
""" create a database connection to a SQLite database """
try:
conn = sqlite3.connect(db_file)
print(sqlite3.version)
except Error as e:
print(e)
finally:
conn.close()
def create_tab... |
import unittest
import triangle_problem
class MyTest(unittest.TestCase):
def test_equilateral_triangle(self):
# Arrange
x = int(10)
y = int(10)
z = int(10)
# Act
receive = triangle_problem.side(x, y, z)
# Assert
self.assertEqual('equilateral', rec... |
def SwapFileData():
f1 = input("Enter the directory of the file to be swapped : ")
f2 = input("Enter the directory of file to swap with : ")
with open(f1 , 'r') as a:
data_a = a.read()
with open(f2 , 'r') as b:
data_b = b.read()
with open(f1 , 'w') as a:
a.write(data_b... |
import random
import os
IMAGES = ['''
+----+
| |
|
|
|
|
==========''', '''
+----+
| |
O |
|
|
|
==========''', '''
+----+
| |
O |
| |
|
|
=========='... |
import matplotlib
import matplotlib.pyplot as plt
import math_lib
def boxplot(L, out_file_name):
"""Generates a boxplot from given data
"""
plt.figure()
plt.boxplot(L)
plt.xlabel('Box')
plt.ylabel('Distribution')
plt.title('Mean: %6.2f, Standard deviation: %6.2f' %
(math_lib.... |
from math import factorial
fatorialn = int(input('Digite um número para calcular seu fatorial: '))
contagem = fatorialn
f = 1
print (f'O fatorial de {fatorialn}! = ', end='')
while contagem > 0:
print ('{}'.format (contagem), end='')
print (' x ' if contagem > 1 else ' = ', end='')
f *= contagem
c... |
lista = [[], []]
for n in range (1, 8):
numeros = int(input(f'Digite o {n}° número: '))
if numeros % 2 == 1:
lista[0].append(numeros)
if numeros % 2 == 0:
lista[1].append(numeros)
print (f'Os números ímpares digitados foram {sorted(lista[0])} ')
print (f'Os números pares digitados foram {so... |
from random import randint
import time
cont = 1
dados = {'jogador 1': randint(1, 6),
'jogador 2': randint(1, 6),
'jogador 3': randint(1, 6),
'jogador 4': randint(1, 6)}
for k, v in dados.items():
print (f'{k} tirou {v}')
time.sleep(0.8)
dadosorg = sorted(dados.items(), key=lambda x: x[1]... |
lista = list()
continuar2 = ' '
while True:
valor = int(input('Digite um valor: ' ))
if valor in lista:
print ('Número já existe, não adicionado...')
else:
lista.append(valor)
print ('Valor adicionado')
continuar = input('Você deseja continuar? [S/N] ').strip().upper()
if con... |
n = int(input('Digite aqui um número inteiro '))
opção = int(input('Você deseja converter para:\n[ 1 ] Binário\n[ 2 ] Octal\n[ 3 ] Hexadecimal:\n'))
if opção == 1:
print ("O seu número {} convertido para binário é {}".format (n, bin(n)[2:]))
elif opção == 2:
print ("O seu número {} convertido para octal é {}".f... |
soma = 0
cont = 0
for impares in range(1, 501, 2):
if impares % 3 == 0:
cont = cont + 1
soma = soma + impares
print (f'A soma de {cont} valores foi {soma}')
|
'''nome = str(input('Digite seu nome completo aqui: ')).strip().lower()
existe = 'silva' in nome
print (f'Em seu nome existe a palavra "Silva"? {existe}')'''
nome1 = str(input('Digite seu nome completo aqui ')).strip().lower()
nomebobo = nome1.split()
existe2 = ('silva' in nomebobo[0])
print = (f'Existe ou não: {exis... |
lista = list()
listai = list()
listap = list()
while True:
lista.append(int(input('Digite um número: ')))
while True:
continuar = input('Você deseja adicionar mais um número? [S/N] ').strip().upper()
if continuar in 'N':
break
if continuar in 'S':
break
if... |
soma = cont = 0
while True:
n = int(input('Digite um número (999 para parar): '))
if n == 999:
break
cont += 1
soma += n
print (f'Foram digitados {cont} números e a soma de todos eles é {soma}')
|
import time
ano = time.gmtime()[0]
maior = 0
menor = 0
for n in range (1, 7+1):
nas = int(input(f'Qual ano a {n}° pessoa nasceu? '))
nas2 = ano - nas
if nas2 >= 21:
maior = maior + 1
elif nas2 <21:
menor = menor + 1
print ('São no total {} pessoas maiores de idade e {} pessoas menores de... |
nomec = str(input('Digite aqui seu nome completo ')).strip()
print ('O nome com todas as letras maiúsculas é: {}'.format(nomec.upper()))
print ('O nome com todas as letras minúsculas é: {}'.format(nomec.lower()))
print ('O número de letras que contém sem considerar espaços é: {}'.format (len(nomec) - nomec.count(' ')))... |
def leiaInt(num):
while True:
try:
n = int(input(num))
except (ValueError, TypeError):
print('\33[31mErro! Digite um número real válido\33[m')
continue
except KeyboardInterrupt:
print('\33[31mO Usuário não digitou os dados\33[m')
re... |
# 用for循环实现1~100求和
sum = 0
# range,左闭右开区间
for i in range(1 ,101):
sum += i
print('1~100的和为:', sum) |
'''
使用tkinter创建GUI
- 使用画布绘图
- 处理鼠标事件
'''
import tkinter
def mouse_evt_handler(evt=None):
row = round((evt.y - 20) / 40)
col = round((evt.x - 20) / 40)
pos_x = 40 * col
pos_y = 40 * row
canvas.create_oval(pos_x, pos_y, 40 + pos_x, 40 + pos_y, fill='black')
top = tkinter.Tk()
# 设置窗口尺寸
t... |
'''
用turtle模块绘图
这是一个非常有趣的模块 它模拟一只乌龟在窗口上爬行的方式来进行绘图
'''
import turtle
turtle.pensize(3)
turtle.penup()
turtle.goto(-180, 150)
turtle.pencolor('red')
turtle.fillcolor('yellow')
turtle.pendown()
turtle.begin_fill()
for _ in range(36):
turtle.forward(200)
turtle.right(170)
turtle.end_fill()
turtle.mainloop() |
# 另一种创建类的方式
def bar(self, name):
self._name = name
def foo(self, course_name):
print('%s正在学习%s.' % (self._name, course_name))
def main():
Student = type('Student', (object,), dict(__init__=bar, study=foo))
stu1 = Student('骆新')
stu1.study('python程序设计')
if __name__ == '__main__':
main()
|
'''
将华氏温度转换为摄氏温度
F =1.8C + 32
'''
f =float(input('请输入华氏温度:'))
c =(f - 32) / 1.8
print('%.1f华氏度 = %.f摄氏度' % (f, c)) |
'''
生成器 - 生成器语法
'''
seq = [x * x for x in range(10)]
print(seq)
gen = (x * x for x in range(10))
print(gen)
for x in gen:
print(x)
num = 10
gen = (x ** y for x, y in zip(range(1, num), range(num - 1, 0, -1)))
print(gen)
n = 1
while n < num:
print(next(gen))
n += 1
|
from itertools import permutations
from math import sqrt
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def sqr_dist(self, other):
"Квадрат расстояния - этого достаточно, чтобы отличать разные расстояния между точками"
return (self.x - other.x)**2 + (self.y - other... |
from math import ceil
def ariphm_sum(start, stop, step=1):
""" Сумма арифметической прогрессии
Аргументы аналогичны функции range, т.е. [start, stop) с шагом step
"""
n = ceil((stop - start) / step)
return (start + step*(n-1)/2) * n
assert ariphm_sum(1, 101) == 5050
assert ariphm_sum(-100, 0) == -5050
assert a... |
import time
def time_passed(func):
def wrap(*args, **kwargs):
start = time.time()
res = func(*args, **kwargs)
end = time.time()
print('Время выполнения: {} секунд.'.format(end-start))
return res
return wrap
from math import ceil
@time_passed
def second_task0(n, x, y, z... |
def compareWithNones(A, B):
for i, row in enumerate(A):
for j, cell in enumerate(row):
b_cell = B[i][j]
if cell is not None and b_cell is not None and cell != b_cell:
return False
return True
_ = None # 0 or 1
A = [
[1, _, 1, _],
[0, 1, _, 0],
[_, 1... |
from random import randint
def new_gladiator(health, rage, damage_low, damage_high):
'''input -> dictionary
Returns a dictionary representing the gladiator with
the provided values: health, rage, lowest damage, and highest damage'''
gladiator = {
'health': health,
'rage': rage,
... |
#encoding=utf-8
'''
Copyright : CNIC
Author : LiuYao
Date : 2017-8-31
Description : test my algorithm
'''
import pandas as pd
import numpy as np
from marchine_learning.linear_model import LogisticRegression
import matplotlib.pyplot as plt
def load_data():
'''
load data
'''
data = pd.read_csv('./data.c... |
n1 = float(input('Primeira nota:'))
n2 = float(input('Segunda nota'))
m = (n1 + n2)/2
print('a primeira nota foi {}, a segunda {} e a media é {}'.format(n1, n2, m))
|
s = float(input('qual o seu salário ? (em reais)'))
if s >= 1250:
a = float((s*10/100) + (s))
print('seu salario é {} e seu almento foi de {}'.format(s, a))
else:
a = float((s*15/100) + (s))
print('seu salario é {} e seu almento foi de {}'.format(s, a))
|
from math import trunc
x = float(input("Digite o numero aqui:"))
k = x*(10**11)
y = (trunc(x))*(10**11)
print("O numero que você digitou foi {},"
" e a sua parte inteira é {}!"
" E a sua parte decimal é {}!" .format(x, trunc(x), (k-y)*(1/(10**11))))
|
x = float(input('Qual o tamanho em metros?'))
print('O tamanho em metros é {}, esse tamanho convertido para centimetros é {} e para milimetros é {}'.format( x, x*100, x*1000))
|
# the function cv2.medianBlur() computes the median of all the pixels under
#the kernel window and the central pixel is replaced with this median value
"""This is highly effective in removing salt-and-pepper noise.
One interesting thing to note is that, in the Gaussian and box filters,
the filtered value for the... |
#!/usr/local/bin/python3
# -*- coding: UTF-8 -*-
class Solution(object):
def test1(self):
'''
题目:有四个数字:1、2、3、4,能组成多少个互不相同且无重复数字的三位数?各是多少?
'''
for i in range(1,5):
for j in range(1,5):
for k in range(1,5):
if( i != k ) and (i != j) and (... |
#Write a function called sumall that takes any number of arguments and returns their sum.
def sumall(*args):
sum=0
for n in args:
sum+=n
return sum
sumall(9,5,6,73) |
import sys
import time
BOARD_SIZE = 20
arg_count=0
def under_attack(col, queens):
return col in queens or \
any(abs(col - x) == len(queens)-i for i,x in enumerate(queens))
#count the LSV for each value
# def least_constraint_value():
#
def rsolve(queens, n):
global arg_count
if n == len(queens)... |
def rotate(lst):
result = [lst[-1]] + lst[0:-1]
return result
# ls = [1, 2, 3, 4]
# print(rotate(ls))
|
import random
class Animal:
animals = set() # Тут будем хранить существующих животных
min_pos, max_pos = 0, 0 # Рамки позиций для животных
def __init__(self, position):
if not (Animal.min_pos <= position < Animal.max_pos):
raise ValueError('Некорректное значение аргумента')
... |
# Функция, возвращающая список с делителями числа
def get_dividers(num):
num = abs(num)
div_list = []
for div in range(- num, num + 1):
if div != 0:
if num % div == 0:
div_list.append(div) # Заполняем список делителей
return div_list
print(*(get_dividers(int(inpu... |
def get_dividers(num):
# Функция, возвращающая список с делителями числа
num = abs(num)
div_list = []
for div in range(-num, num + 1):
if div:
if not num % div:
div_list.append(div) # Заполняем список делителей
return div_list
def is_prime(num):
# Функция,... |
# -*- coding: utf-8 -*-
class node:
def __init__(self,key,p=None):
self.p = p
self.key = key
self.right = None
self.left = None
self.height = 0
def __str__(self):
return "Key: "+str(self.key)
def checkparent(self):
if self.p == None:... |
import math
import numpy as np
def reverse(L):
if len(L) == 0:
return []
return [L[-1]] + reverse(L[:-1])
def is_sorted(L):
if len(L) <= 1:
return True
elif L[0] > L[1]:
return False
return is_sorted(L[1:])
def print_binary(string_so_far,digits_left):
... |
#Student: Sosa, Thomas
# Course: CS 2302 Data Structures
#Date of last modification: September 17
# Assignment: Lab 1 Recursion
# TA: Anindita Nath
# Professor: Olac Fuentes
# Purpose: The purpose of this lab is to understand recursion uses stack to work
import numpy as np
import matplotlib.pyplot as plt
import math
i... |
#total_secs = int(input("How many seconds, in total? "))
#hours = total_secs // 3600
#secs_still_remaining = total_secs % 3600
#minutes = secs_still_remaining // 60
#secs_finally_remaining = secs_still_remaining % 60
#
#print("Hrs=", hours, "mins=", minutes, "secs=", secs_finally_remaining)
|
def set_level(level):
return level * '\t'
if __name__ == '__main__':
alphabet = int(input('Quantos símbolos no alfabeto? '))
symbols = ['' for i in range(alphabet)]
for i in range(alphabet):
symbols[i] = input(f'Qual é o símbolo {i}? ')
states_amount = int(input('Quantos estados? '))
... |
import threading
import multiprocessing
import time
def Fibonacci_driver(n):
if n<0:
print("Invalid Input")
elif n==1:
return 0
elif n==2:
return 1
else:
return Fibonacci_driver(n-1)+Fibonacci_driver(n-2)
def Fibonacci(n):
print(f"Fib {n} is {Fibonacci_driver(n)}")
if __name__ == "__main__":
... |
Users = {
'huy' : {
'name' : 'Nguyen Quang Huy',
'age' : 29
},
'don' : {
"name" : 'Don zoombie',
'age' : 23
},
'tuong' : {
'name' : "Đào Cí Cươ",
'age' : 15
}
}
def... |
import urllib2
from PIL import Image, ImageOps, ImageDraw
import ssl
import os
# Download the user's facebook image
def download(id):
url = "https://graph.facebook.com/"+id+"/picture?height=200&width=200"
# evil - bypass ssl certification
ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mo... |
a = int(input("starts from:- "))
b = int(input("to:- "))
c = ('0','2','4','6','8')
d = ('1','3','5','7','9')
while(str(a).endswith(c)):
print (a)
a = a+2
if(a>b):
break
continue
while(str(a).endswith(d)):
print (a+1)
a = a+2
if(a>=b):
break
continue
|
import random
def main():
welcome()
name_of_player = player_name()
guessing_number = []
for number in random_number():
guessing_number.append(number)
print(guessing_number)
guessing(name_of_player, guessing_number)
def welcome():
print("Hi there!\n"
"I've generated a ra... |
# -*- coding: utf-8 -*-
"""
HackerRank - Frequency Queries
https://www.hackerrank.com/challenges/frequency-queries
Created on Sun Dec 9 14:01:48 2018
@author: Arthur Dysart
"""
## REQUIRED MODULES
from collections import defaultdict
import sys
## MODULE DEFINITIONS
class Solution:
"""
It... |
# -*- coding: utf-8 -*-
"""
HackerRank - Sock Merchant
https://www.hackerrank.com/challenges/sock-merchant
Created on Mon Nov 12 22:29:31 2018
@author: Arthur Dysart
"""
## REQUIRED MODULES
from collections import Counter
import sys
## MODULE DEFINITIONS
class Solution:
"""
Iteration over... |
# bubblesort.py
def bubbleSort(array):
n = len(array)
# Traverse all the array elements
for i in range(n-1, 0, -1):
for j in range(i):
if array[j] > array[j + 1]:
array[j], array[j + 1] = array[j + 1], array[j]
|
def repeat_string(string, count):
print(f'{string}' * count)
text = input()
repeated = int(input())
repeat_string(text, repeated) |
degrees = int(input())
time_of_day = input()
outfit = None
shoes = None
if (10 <= degrees <= 18) and (time_of_day == "Morning"):
outfit = "Sweatshirt"
shoes = "Sneakers"
elif (10 <= degrees <= 18) and (time_of_day == "Afternoon"):
outfit = "Shirt"
shoes = "Moccasins"
elif (10 <= degrees <= 18) and (ti... |
budget = float(input())
statist = int(input())
price = float(input())
dekor = 0.10 * budget
clothing = statist * price
if statist > 150:
discount = 0.10 * clothing
total_clothing = clothing - discount
total_movie = dekor + total_clothing
money = abs(budget - total_movie)
else:
total_movie = dek... |
price_flour = float(input())
kg_flour = float(input())
kg_sugar = float(input())
eggs = int(input())
yeast = int(input())
price_sugar = price_flour * 0.75
price_eggs = price_flour * 1.1
price_yeast = price_sugar * 0.2
summ_flour = price_flour * kg_flour
summ_sugar = price_sugar * kg_sugar
summ_eggs = price_eggs * egg... |
import sys
n = int(input())
max_number = -sys.maxsize - 1
min_number = sys.maxsize
for num in range(n):
current_number = int(input())
if current_number > max_number:
max_number = current_number
if current_number < min_number:
min_number = current_number
print(f"""Max number: {max_numbe... |
decimal_list = list(map(float, input().split()))
restart = True
while restart:
index_counter = 1
for num in decimal_list:
if index_counter >= len(decimal_list):
restart = False
break
if num == decimal_list[index_counter]:
decimal_list[index_counter] = floa... |
area_yard = float(input())
price_yard = area_yard * 7.61
discount = price_yard * 0.18
final_price = price_yard - discount
print(f'The final price is: {final_price:.2f} lv.')
print(f'The discount is: {discount:.2f} lv.') |
def multiply_evens_by_odds(number):
even_sum = 0
odd_sum = 0
for digit in str(number):
last_number = abs(number) % 10
if last_number % 2 == 0:
even_sum += last_number
else:
odd_sum += last_number
number = abs(number) // 10
return even_sum * odd... |
x_1 = float(input())
y_1 = float(input())
x_2 = float(input())
y_2 = float(input())
x = float(input())
y = float(input())
if (x == x_1 or x == x_2) and (y_1 <= y <= y_2):
print("Border")
elif (y == y_1 or y == y_2) and (x_1 <= x <= x_2):
print("Border")
else:
print("Inside / Outside") |
import datetime
birthday_one = input()
datetime_object = datetime.datetime.strptime(birthday_one, '%d-%m-%Y').date()
modified_date = datetime_object + datetime.timedelta(days=1000)
date = modified_date.strftime("%d-%m-%Y")
print(date)
|
campaign = int(input())
confectioners = int(input())
cakes = int(input())
waffles = int(input())
pancakes = int(input())
cakes = cakes * 45
waffles = waffles * 5.80
pancakes = pancakes * 3.20
total_day = (cakes + waffles + pancakes) * confectioners
total_campaign = total_day * campaign
net = total_campaign - 1 / 8 * ... |
number = float(input())
unit_input = input()
unit_output = input()
if unit_input == "mm" and unit_output == "m":
result = number / 1000
elif unit_input == "mm" and unit_output == "cm":
result = number / 10
elif unit_input == "m" and unit_output == "cm":
result = number * 100
elif unit_input == "m" and u... |
import math
vineyard = int(input())
grapes_meter = float(input())
needed_liters = int(input())
workers = int(input())
total_grapes = vineyard * grapes_meter
wine_produced = (0.40 * total_grapes) / 2.5
if wine_produced < needed_liters:
lack_wine = needed_liters - wine_produced
print(f"It will be a tough winte... |
for letter in range(ord("a"), ord("{")):
print(chr(letter)) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.