text stringlengths 37 1.41M |
|---|
from tkinter import simpledialog, messagebox, Tk, Canvas
import math
# Write a Python program that asks the user for the radius of a circle.
# Next, ask the user if they would like to calculate the area or circumference of a circle.
# If they choose area, display the area of the circle using the radius.
# Otherw... |
# Тип данных строка (str)
# Инициализация
temp_str = 'Марка авто "Volvo"'
print(temp_str)
# Экранирование
#temp_str = 'Марка авто \'Volvo\'
# Обращение к символам, подстрокам
# выведет в кажд-ю строку, одну букву. Вывод ПОСИМВОЛЬНО
for i in range(len(temp_str)):
print(temp_str[i])
# Срезы
print... |
# Тип данных Словарь dict
dict_temp = {}
print(type(dict_temp), dict_temp)
dict_temp = {'dict': 1, 'dict2': 2.1, 'dict3': 'name', 'dict4': [1, 2, 3]}
print(type(dict_temp), dict_temp)
print(' * ')
dict_temp = dict.fromkeys(['a', 'b']) # fromkeys создает словарь с КЛЮЧАМИ без ЗНАЧЕНИЙ
print(type(dict_temp), dict_tem... |
#TP4 : Table de Multiplication
#Exercice 1 : Open Class Room
#Src : https://openclassrooms.com/fr/courses/235344-apprenez-a-programmer-en-python/231442-avancez-pas-a-pas-vers-la-modularite-1-2
import os
def multipl(number,max=11):
"""
docstring de la fonction multipl :
Table de multiplication
... |
from random import randint
# available weapons => store this in an array
choices = ["Rock", "Paper", "Scissors"]
player = False
player_lives = 5
computer_lives = 5
# make the computer pick one item at random
computer = choices[randint(0, 2)]
# show the computer's choice in the terminal window
print("computer choos... |
from playsound import playsound
import keyboard
def sound():
playsound('') #add the name of the mp3 file here, you want to play when you press the buton.
exit = True
while (exit):
if(keyboard.is_pressed('space')): #Change here for which button you want to play the mp3 file.
sound()
exit = not... |
import time
import requests
from datetime import datetime
import billboard
""" File that reads in a date from the command line and
finds the top song on that day for all years since that date"""
def validate_input(bday_raw):
""" Validates string passed is a valid birthday
Returns: tuple containing (inv... |
n=int(input("enter te no.plz"))
for i in range(0,n+1):
print (" "*(n-i),"*"*(i*2-1))
for i in range(n-1,0,-1):
print (" "*(n-i),"*"*(i*2-1))
|
n=int(input("enter the value of list : "))
l=[]
for i in range(0,n):
a=int(input("value of list : "))
l.append(a)
l.sort()
print(l)
c=0
l2=[]
for i in range(0,n-1):
if l[i+1] == l[i]:
l2.append(l[i])
l2.sort()
print(l2)
l3=[]
for i in range(0,n-1):
if l[i+1] != l[i]:
... |
short_names = ['Jan', 'Sam', 'Ann', 'Joe', 'Tod']
short_names.sort()
short_names.reverse()
print(short_names) |
from Stack import Stack
def main():
stack = Stack()
stack.push(0)
assert stack.data == [0, None]
assert stack.capacity == 2
assert stack.size == 1
stack.push(1)
assert stack.data == [0, 1]
assert stack.capacity == 2
assert stack.size == 2
stack.push(2)
assert stack.data ... |
def high_and_low(numbers):
numbers_arr = numbers.split(" ")
numbers_arr = [int(num) for num in numbers_arr]
high_number = numbers_arr[0]
low_number = numbers_arr[0]
for num in numbers_arr:
if(num > high_number):
high_number = num
low_number = high_number
for num i... |
import numpy as np
class Mullayer:
def __init__(self):
self.x=None
self.y=None
def forward(self,x,y):
self.x=x
self.y=y
out=x*y
return out
def backward(self,dout):
dx=dout*self.y
dy=dout*self.x
return dx,dy
'''
apple=100
a... |
import numpy as np
import matplotlib.pylab as plt
def function_1(x):
return x**3
def function_2(x,k,b):
return k*x+b
def function_3(f1,k,x):
return f1(x)-k*x
def numerical_diff(f,x):
h=0.0001
return (f(x+h)-f(x-h))/(2*h)
def k_line(f1,x,c):
k=numerical_diff(f1, c)
b=function_3(f1,k,c)
z... |
# https://www.hackerrank.com/challenges/arrays-ds/problem
# Complete the reverseArray function below.
def reverseArray(a):
a = reversed(a)
return a |
#!/usr/bin/env python3
def main():
szam = input("Szám: ")
print(int(str(szam)[::-1]))
if __name__ == ('__main__'):
main()
|
def ciklus(start, end, debug=False):
if debug:
print('#ciklus kezdete')
inp = [str(n ) +',' for n in range(start, end + 1)]
print(''.join(inp)[:-1])
if debug:
print('#ciklus vége')
def main():
ciklus(1, 10)
ciklus(1, 10, True)
if __name__ == '__main__':
main()
|
#!/usr/bin/env python3
def main():
x = input('Páros szám:')
print(str(diamond(x)))
def diamond(x):
if int(x) % 2 == 0:
return 'Csak páratlan számok!'
else:
n = ''
for i in range(1, int(x)+1, 2):
subs = '*' * i
n = n + subs.center(int(x)+1) + '\n'
... |
""" Create a list of five IP addresses.
Use the .append() method to add an IP address onto the end of the list. Use the .extend() method to add two more IP addresses to the end of the list.
Use list concatenation to add two more IP addresses to the end of the list.
Print out the entire list of ip addresses. Print ou... |
import numpy as np
import cv2
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
# TODO 2. Use color transforms, gradients, etc., to create a thresholded binary image.
# Define a function that applies Sobel x or y,
# then takes an absolute value and applies a threshold.
def abs_sobel_thresh(img_gray, or... |
list1 = ["b", "c"]
dict1 = {"b":1, "c":2, "d":3}
keys = list(dict1.keys())
# list1とdict1の一致要素
test1 = [l1 for l1 in list1 if l1 in keys]
print(test1)
test1plus = list(set(list1) & set(keys))
print(test1plus)
# list1にあってdict1にない要素
test2 = [l1 for l1 in list1 if l1 not in keys]
print(test2)
test2plus =... |
# 台形法による数値積分
# 関数f(x)
def f(x):
return 3 * x ** 2 + 10
# 台形法
def trapezoidal(a, b, n):
h = (b - a) / n # 微小区間
G = h / 2 * ((f(a) + f(b)) + 2 * sum(f(a + h * i) for i in range(1, n)))
return G, h
# 区間の設定
a = 1.0
b = 3.0
# 入力
n = int(input('定義域内の分割数(整数)を入力してください'))
# 結果の出力
print('結果および微小区間hは', *trape... |
#!/usr/bin/env python
from ants import *
from Graph import GraphNode
from Graph import Graph, RectGrid
import random
import time
# define a class with a do_turn method
# the Ants.run method will parse and update bot input
# it will also run the do_turn method for us
class MyBot:
def __init__(self):
# defi... |
#!/usr/local/bin/python
# -*- coding: UTF-8 -*-
import random, string, time
import names, place_name_generator
def make_ghost(place=None, current_year=None):
#set up some basic stuff first of all...
if place == None:
#make something up...
place = place_name_generator.make_name()
... |
'''
Blockchain
A Blockchain is a sequential chain of records, similar to a linked list.
Each block contains some information and how it is connected related to the other blocks in the chain.
Each block contains a cryptographic hash of the previous block, a timestamp, and transaction data.
For our blockchain we will ... |
# Задание-1:
# Реализуйте описаную ниже задачу, используя парадигмы ООП:
# В школе есть Классы(5А, 7Б и т.д.), в которых учатся Ученики. У каждого ученика есть два Родителя(мама и папа).
# Также в школе преподают Учителя, один учитель может преподавать в неограниченном кол-ве классов
# свой определенный предмет. Т.е. У... |
# Задача-1:
# Дан список фруктов.
# Напишите программу, выводящую фрукты в виде нумерованного списка,
# выровненного по правой стороне.
# Пример:
# Дано: ["яблоко", "банан", "киви", "арбуз"]
# Вывод:
# 1. яблоко
# 2. банан
# 3. киви
# 4. арбуз
# Подсказка: воспользоваться методом .format()
newList = ["яблоко", "... |
import pandas as pd
import matplotlib.pylab as plt
import numpy as np
# Read data from csv
pga = pd.read_csv("pga.csv")
# Normalize the data 归一化值 (x - mean) / (std)
pga.distance = np.linspace(300, 0, 197) + np.random.random(197)*50
pga.accuracy = np.linspace(100, 200, 197) + np.random.random(197)*50
pga.distance = (... |
import matplotlib.pylab as pyl
import numpy as np
def operation():
pass
if __name__ == '__main__':
X_ = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9])
Y_ = np.array([1, 2.3, 2.7, 4.3, 4.7, 6.3, 7, 8, 9])
# X_ = np.array([1])
# Y_ = np.array([1])
n = len(X_)
for i in range(3):
x_ = X_[i... |
from display import *
from matrix import *
from draw import *
"""
Goes through the file named filename and performs all of the actions listed in that file.
The file follows the following format:
Every command is a single character that takes up a line
Any command that requires arguments must have tho... |
#!/usr/bin/python3
import sqlite3
db = "./students.db"
conn = sqlite3.connect(db)
c = conn.cursor()
cmd = "CREATE TABLE students (Name TEXT, Last TEXT)"
c.execute(cmd)
conn.commit()
data = [
("Robert", "Tables"), ("Toby", "Huang"), ("Hannah", "Sindorf"),
("Daniel", "Frey"), ("Ray", "Ruazol"), ("Roger", "Huba"),... |
from pygame import display, draw, time, event
from pygame import KEYDOWN
import random
class Circle:
def __init__(self, center, radius):
self.center = center
self.radius = radius
screen = display.set_mode([800, 600])
screen.fill([0]*3) # RGB
white = [255, 255, 255]
'''
center = [400, 300]
radiu... |
import rooms
import barriers
import objects
import items
import player
class adventure:
def __init__(self, y=1, x=1):
self.x = x
self.y = y
self.map = []
for i in range(2*y+1):
self.map.append([])
for j in range(2*x+1):
self.map[i].ap... |
name = input("Please enter your name. > ")
print("Hello, " + name.split(" ")[0].title() + "!")
x = input("Give me an integer to add: ")
try:
x = int(x)
except:
print("The value you entered is not a number.")
else:
y = input("Give me another integer to add: ")
try:
y = int(y)
except:
print("The second valu... |
#####################
### Base classes. ###
#####################
class room:
repr = "room"
m_description = "You are in a simple room."
def __init__(self, contents=[]):
self.contents = contents
def __str__(self):
s = ""
for object in self.contents:
... |
# logic operator
# конструкция if
test = 'String'
if test:
print('hello, world')
human = 100
robots = 1000
if robots > human: #если роботов больше чем людей
print('all right')# если роботов действительно больше(если переменная robots больше чем переменная human) выводить на экран это сообщ
# конструкция else
... |
class Person:
name =''
surname =''
quality = 0
def __init__(self, n, s, q):
self.name = n
self.surname = s
self.quality = q
def showPerson(self):
print(self.name, self.surname, self.quality, 'количество трудового стажа в годах')
def __del__(self):
delit = int(input('Введите номер сотрудникаn\nNikla... |
from tkinter import *
import os
creds = 'tempfile.temp' # This just sets the variable creds to 'tempfile.temp'
failure_max = 3
def delete3():
screen4.destroy()
def password_not_recognised():
global screen4
screen4 = Toplevel(screen)
screen4.title("Access Denied")
screen4.geome... |
#This program imports data from a link, cleans the data and then generates a boxplot, histogram and QQ-Plot for a specific column of the data
#each plot is saved and printed to the screen
#Observations: From the boxplot and histogram it is apparent that the data is skewed right (mean<median).
#Observations (cont'd): ... |
name='helen'
name1= name.capitalize()
print(name1)
title='GREATWALL'
title2=title.casefold()
print(title2)
name='Helen'
name.count('e')
fname='string.py'
x=fname.endwith('.py')
print(x)
s1='238'
s2='ww2'
s1.isnumeric()
s2.isnumeric()
a=''
while not a.isnumeric():
print('please input a number:')
a=input()
n... |
from os import get_terminal_size
print('a good day')
print('helen')
name='helen'
print('hello '+ name)
print(f'hello {name}')
air='off'
temp=92
too_hot=temp>95
if too_hot:
air='on'
print('too hot')
temp=92
air=''
if temp>90:
air='on'
else:
air='off'
print(air)
temp=65
go_out= False
if temp>=50 a... |
def print_factors(a):
for i in range(1,a+1):
if a % i ==0:
print(i)
print_factors(100)
def factors(a):
la=[]
for i in range(1,a+1):
if a%i==0:
la.append(i)
return la
la=factors(20)
print(la)
def welcome(school='GMS', student)
print(f'{school} welcome {stud... |
import numpy as np
import pandas as pd
import re #class for regular expression
from nltk.corpus import stopwords
# stopwords are wirds like the, is etc. that do not have any importance while classifying emails as spam or not
STOPWORDS = set([]) # set(stopwords.words('english'))
def clean_text(text):
text = text.... |
def jumpingOnClouds(c):
count = 0
i = 0
while True:
if i+2 < len(c) and c[i+2] == 0:
count += 1
i = i+2
print('count: ', count, 'jumps:', 2, 'increment:', i)
elif i+1 < len(c) and c[i+1] == 0:
count += 1
i = i+1
print('... |
#python program to classify the handwritten digits (MNIST Dataset) using pytorch and GPU
import torch
import matplotlib.pyplot as plt
import numpy as np
import torchvision #importing the dataset
import torchvision.transforms as transforms #transform the dataset to torch.tensor
import torch.optim as optim # for ... |
import random
N = int(input("Please eneter a number : "))
Counter = 1
Numbers = []
Numbers.append(random.randint( 0, 1000))
while Counter < N :
Duplicate = False
Rnd = random.randint(0, 1000)
for i in range(len(Numbers)) :
if Numbers[i] == Rnd :
Duplicate = True
... |
# This file generates data to use in `intro_to_pandas.py` file.
# NOTE: This file is used to generate random data in csv file. You can modify this file
# according to your requirement. Add/update/delete values in `list_of_columns`, which
# stores column detail and generate data for that column according to given detai... |
import tensorflow as tf
import numpy as np
from tensorflow.examples.tutorials.mnist import input_data
import os
a = tf.constant([.0,.0,.0,.0], tf.float32)
b = tf.constant([1.,2.,3.,4.], tf.float32)
result1 = tf.nn.softmax(a)
result2 = tf.nn.softmax(b)
sess = tf.Session()
print(sess.run(result1))
print(sess.run(resu... |
APPROVED = ['firstNames.txt', 'lastNames.txt']
def getEntries(file):
# returns a list of entries from filename
file.seek(0)
file.readline() #skip past entry count
entries = []
for line in file:
entries.append(line.rstrip())
return entries
def deleteContent(file):
file.seek(0)
file.truncate()
def... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
list001=range(101)
a=0
n=int(input("请输入准备取前几个数:"))
list002=[]
while a<n:
list002.append(list001[a])
a=a+1
print(list002)
|
#--coding:utf-8--
h=input("请输入你的身高\n")
kg=input("请输入你的体重\n")
h=float(h)
kg=float(kg)
bmi=kg/(h*h)
if bmi<18.5 :
print("过轻")
elif bmi<=25 :
print("正常")
elif bmi<=28:
print("过重")
elif bmi<=32:
print("肥胖")
elif bmi>32:
print("严重肥胖")
|
#! /usr/bin/env python3
# coding=utf-8
name=input("请输入你的名字!:")
age=int(input("请输入你的年龄:"))
a_dict={'testname':29}
a_dict[name]=age
print(a_dict)
|
#! /usr/bin/env python3
# coding=utf-8
sum=0
for x in [1,2,3,4,5,6,7,8,9,10]:
sum=sum+x
print(sum)
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
L1=['Hello','World',18,'Apple',None]
L2=[s.lower() for s in L1 if isinstance(s,str) ]
print(L2)
|
class simpleOperations(object):
def __init__(self, x,y):
self.x = x
self.y = y
# all of simple operations can call x because of this self function
def productXY(self):
prod = [self.x[i]*self.y[i] for i in range(len(self.x))]
return prod
def addOneX(s... |
#!/usr/local/bin/python
# given a list of integers, prints fizz for any value that is a multiple of 3
# prints buzz for any value that is a multiple of 5, and for any value that
# is a multiple of 3 and 5 prints fizzbuzz
import sys
for numstr in sys.argv[1:]:
num = int(numstr)
if num % 3 == 0 and num % 5 == ... |
#Python program to count number of characters in a string.
a = input("Enter the string :")
f = {}
for i in a:
if i in f:
f[i] += 1
else:
f[i] = 1
print ("Count of all characters is :\n "+str(f))
#Output
#Enter the string :afxghbk
#Count of all characters is :
# {'a': 1, 'f':... |
# Examine the code below.
# What is it doing?
# Could you make this code better?
def printevens(x):
y = 0
while(y < len(x)):
if y % 2 == 0:
print(x[y], end=" ")
y += 1
|
#Imagine you are creating a program to give advice about
# what activities to do based on the weather
#TODO: Write some code to check what the weather is
# today and print out what to do if the weather is sunny
# then print "Let's go to the park!" if the weather is
# foggy print "Let's go see a movie" if the weath... |
# Homework: Create a madlib. Imagine a story where some of the words are
# supplied by user input. Using python you will use input to collect
# words for a story and then display the story.
# Use input to collect each word to a variable
# Use an f string to display the story
# Your madlib must collect at least 6 ... |
# Homework: Your job is to make a custom calculator.
# Your calculator should accept at least three values.
# For example height, width, length
# It should print a prompt that makes it clear what
# is being calculated.
# For example:
# Enter height, width, and length to calculate the area of a cube
# Height: 3
... |
numbers = [2,15,0,-3]
def insertion_sort(arr):
for iterater in range(len(arr)):
#the variable cursor is assigned the value of the iterater for each int in numbers
cursor = (arr[iterater])
#the variable position is assigned the index of each num in numbers list
position = iterater
while posit... |
class TreeNode(object):
def __init__(self, key, val, left=None, right=None, parent=None):
self.key = key
self.payload = val
self.left_child = left
self.right_child = right
self.parent = parent
def has_left_child(self):
return self.left_child
def has_right_ch... |
import unittest
from Implementation.binary_tree import BinaryTree
class MyTestCase(unittest.TestCase):
def test_something(self):
r = BinaryTree('a')
self.assertEqual(r.get_root_value(), 'a')
self.assertEqual(r.get_left_child(), None)
self.assertEqual(r.get_right_child(), None)
... |
from PyQt5.QtWidgets import *
from PyQt5 import QtCore, QtGui
from PyQt5.QtGui import *
from PyQt5.QtCore import *
import copy
import tictactoe
from minimax import MiniMax
import sys
# Create window class
class Window(QMainWindow):
#constructor
def __init__(self):
super().__init__()
# setting ... |
# Merge Sort
def merge_sort(arg):
if len(arg) > 1:
mid = len(arg) // 2
lx = arg[:mid]
rx = arg[mid:]
merge_sort(lx) # Divide Left side
merge_sort(rx) # Divide Right side
li, ri, i = 0,0,0
while li < len(lx) and ri < len(rx):
if lx[li] > rx[ri... |
#Problem 15
"""
Q. John works at a clothing store and he's going through a pile of socks to find the number of
matching pairs. More specifically, he has a pile of n loose socks where each sock i is labeled
with an integer, ci, denoting its color. He wants to sell as many socks as possible, but his
cust... |
def solution(record):
answer = []
dic = dict()
for data in record:
cmd = data.split(' ')[0]
if cmd == 'Enter' or cmd == 'Change':
cust_id = data.split(' ')[1]
nick = data.split(' ')[2]
dic[cust_id] = nick
for data in record:
cmd = data.spli... |
# Problem 20
"""
Q. Given an array of integers, find and print the maximum number of integers you can select from
the array such that the absolute difference between any two of the chosen integers is <=1.
Input
The first line contains a single integer, n, denoting the size of the array.
T... |
from datetime import date
def access(user_birthday):
"""
Checks the user's age. If more than 13,
it allows access, otherwise blocked user.
:param user_birthday: user birthday in
datetime format
:return user access
"""
if user_birthday:
curr_year = date.today().year
age ... |
#board is a list of rows of the same size.
#each entry of board is 0 (invalid move) or 1 (valid move).
#the function should return a valid move, for example [0,0] (which is a loosing move, of course)
def move(board):
import random
moves = []
real_width=len(board[0])
for i in range (0,len(board)):... |
n = int(input())
parents = dict()
childs = dict()
def read():
cl = input()
st = ''
for i in range(len(cl)): # разбили на созданный класс и его предков
if cl[i] == ' ':
st = cl[i + 3:]
cl = cl[:i]
break
if cl not in parents:
parents[cl] = set()
... |
from xml.etree import ElementTree as Et
s = input()
root = Et.fromstring(s)
colors = {'red': 0, 'green': 0, 'blue': 0}
def func(elem, val):
attr = elem.attrib
colors[attr['color']] += val
for child in elem:
func(child, val + 1)
func(root, 1)
for val in colors.values():
print(val, end = ' ... |
choice_of_operation = input('Enter 1 for addition and 2 for subtraction, enter 3 for multiplication and 4 for division. ')
if choice_of_operation == '1':
value_1 = input('What is the value of the first number? ')
value_2 = input('What is the value of the second number? ')
print(float(value_1) + float(va... |
# -*- coding: utf-8 -*-
"""
Created on Wed Mar 24 09:48:32 2021
@author: raj patil
"""
for i in range(int(input())):
n = input()
if n == n[::-1]:
print('wins')
else:
print('loses')
|
# -*- coding: utf-8 -*-
"""
Created on Mon Mar 15 13:43:51 2021
@author: raj patil
"""
t = int(input())
for i in range(t):
sum = 0
num = input()
sum = sum + int(num)%10 + int(num)//pow(10,len(num) - 1)
print(sum) |
def gradingStudents(grades):
for i in range(len(grades)):
current = grades[i]
if (current < 38) or (current % 5) < 3:
pass
else:
grades[i] = (current + 5) - (current % 5)
return grades
# OR
# return [max(n, (n + 2) // 5 * 5) if n >= 38 else n for ... |
import tkinter as tk
import random
import sys
class Category:
def __init__(self,filein,fileout):#contains two parameters:input file and output file
wordlist=filein.readlines()#read the document into a list of lines
#instance variables include the output file, list of lines, dictionary of advance lev... |
import string
t0 = dir(string)
t = t0 [-5:]
print ("This is TUPLE: ", tuple (t))
print ("This is LIST: ",list (t))
t.insert (2,"capwords")
print ("The result is: ", tuple (t))
|
from random import randint
def set_doors():
l = ['g','g','g']
a = randint(0,2)
l[a] = 'c'
return l
def player_first_choice():
'''
this code returns an integer that is the player's choice
'''
first = randint(0,2)
return first
def host_show_goat(l,first):
'''
... |
# Второй максимум
# Последовательность состоит из различных натуральных
# чисел и завершается числом 0. Определите значение
# второго по величине элемента в этой последовательности.
# Гарантируется, что в последовательности есть хотя бы
# два элемента.
max1 = int(input())
max2 = 0
b = 1
while b != 0:
b = int(... |
# Високосный год
# Дано натуральное число. Требуется определить, является ли год с данным номером високосным.
# Если год является високосным, то выведите YES, иначе выведите NO. Напомним, что в
# соответствии с григорианским календарем, год является високосным, если его номер кратен 4,
# но не кратен 100, а также ес... |
# Удалить элемент
# Дан список из чисел и индекс элемента в списке k.
# Удалите из списка элемент с индексом k, сдвинув
# влево все элементы, стоящие правее элемента с
# индексом k.
# Программа получает на вход список, затем число k.
# Программа сдвигает все элементы, а после этого
# удаляет последний элемент спи... |
# Шахматная доска
# Даны два числа n и m. Создайте двумерный массив
# размером # n×m и заполните его символами "." и
# "*" в шахматном порядке. В левом верхнем углу
# должна стоять точка.
n, m = [int(i) for i in input().split()]
l_list = [['*' for i in range(m)] for j in range(n)]
for i in range(n):
for j in ... |
# Утренняя пробежка
# В первый день спортсмен пробежал x километров, а затем
# он каждый день увеличивал пробег на 10% от предыдущего
# значения. По данному числу y определите номер дня, на
# который пробег спортсмена составит не менее y километров.
# Программа получает на вход действительные числа x и y и
# должна... |
# Проценты
# Процентная ставка по вкладу составляет P процентов
# годовых, которые прибавляются к сумме вклада. Вклад
# составляет X рублей Y копеек. Определите размер вклада
# через год.
# Программа получает на вход целые числа P, X, Y и должна
# вывести два числа: величину вклада через год в рублях и
# копейках.... |
# Часы - 3
# С начала суток часовая стрелка повернулась на
# угол в α градусов. Определите сколько полных
# часов, минут и секунд прошло с начала суток,
# то есть решите задачу, обратную задаче «Часы -
# 1». Запишите ответ в три переменные и выведите
# их на экран.
angle = float(input())
H = angle // 30
M = (ang... |
# Больше своих соседей
# Дан список чисел. Определите, сколько в этом
# списке элементов, которые больше двух своих
# соседей, и выведите количество таких элементов.
# Крайние элементы списка никогда не учитываются,
# поскольку у них недостаточно соседей.
a_list = [int (i) for i in input().split()]
count = 0
for... |
# Минимум из трех чисел
# Даны три целых числа. Выведите значение наименьшего из них.
a = int(input())
b = int(input())
c = int(input())
if a <= b and a <= c:
print(a)
elif b <= a and b <= c:
print(b)
elif c <= a and c <= b:
print(c) |
# Первая цифра после точки
# Дано положительное действительное число X. Выведите
# его первую цифру после десятичной точки.
import math
x = float(input())
first = int((x - int(x)) * 10)
print(first) |
# Обращение фрагмента
# Дана строка, в которой буква h встречается как
# минимум два раза. Разверните последовательность
# символов, заключенную между первым и последним
# появлением буквы h, в противоположном порядке.
s = input()
h1Pos = s.find('h')
hLPos = s.rfind('h')
sWithoutH = s[h1Pos + 1:hLPos]
sNew = s[0... |
# Шоколадка
# Шоколадка имеет вид прямоугольника, разделенного
# на n×m долек. Шоколадку можно один раз разломить
# по прямой на две части. Определите, можно ли таким
# образом отломить от шоколадки часть, состоящую
# ровно из k долек. Программа получает на вход три
# числа: n, m, k и должна вывести YES или NO.
n... |
from statistics import mean, median, mode, stdev, StatisticsError
def prompt(value_type):
return input("Please input a {}. Blank line to end: ".format(value_type))
def string_length_stats(strings):
lengths =[]
for string in strings:
lengths.append(len(string))
return {'min':min(lengths),'max':... |
import logging
def sum(n):
if not n: #empty string
logging.debug("empty string. return 0")
return 0
else:
logging.debug("first digit: {} invoking func with remaining string: {}".format(n[0], n[1:]))
intermediate_sum = (int(n[0]) + sum(n[1:]))
logging.debug("intermediate_sum: {}".format(intermediate_sum))
... |
password="kevin"
guess=""
print "WELCOME TO THE KEVSMART ATM, ENJOY YOUR STAY!"
print ""
while (password!=guess):
guess=raw_input("Enter the password: ")
print ""
print("Access Granted")
print ""
canaccount=100.00
usaccount=100.00
while True:
print "Current value of Canadian account is $",canaccount
print ""
... |
import sqlite3
def db_connect(sqlite_file):
""" Make connection to an SQLite database file """
return sqlite3.connect(sqlite_file)
def db_close(conn):
""" Close connection to the database """
conn.close()
def db_init(conn):
""" Create table and delete yesterday's not done tasks """
cur = c... |
boletim = list()
dados = list()
notas = list()
while True:
print(f'Aluno {len(boletim)+1}: ')
dados.append(str(input('Nome: ')).strip().capitalize())
notas.append(float(input('1ª nota: ')))
notas.append(float(input('2ª nota: ')))
dados.append(notas[:])
boletim.append(dados[:])
notas.clear()
... |
altura = float(input('Informa a altura (em metros): '))
largura = float(input('Informe a largura (em metros): '))
area = altura * largura
print('altura = {:.3f} mt, largura = {:.3f}mt, área = {:.3f} m²'.format(altura, largura, area))
print('serão necessários {:.3f} litros de tinta para a pintura.'.format(area/2))
|
v = int(input('Informe um valor inteiro: '))
print('O sucessor de {} é {}'.format(v, v+1))
print('O antcessor de {} é {}'.format(v, v-1))
|
n1 = int(input('Informe o primeiro número: '))
n2 = int(input('Informe o segundo número: '))
n3 = int(input('Informe o terceiro número: '))
nme = n1
nma = n1
if nme > n2:
nme = n2
if nme > n3:
nme = n3
if nma < n2:
nma = n2
if nma < n3:
nma = n3
print('O menor número é {} e o menor é {}'.format(nme, nma... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.