text stringlengths 37 1.41M |
|---|
import random
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from collections import namedtuple
from itertools import combinations
class TSPGA(object):
"""
Travel Salesman Problem using Genetic Algorithm
Parameters
----------
generation : int
number of iteration to train the algorithm
... |
# Associate youtube video
# https://www.youtube.com/watch?v=0Keq3E2bbeE
# https://www.youtube.com/watch?v=hKuw-8Gjwjo
import unittest
def my_contains(elem, lst):
"""Returns True if and only if the element is in the list"""
return elem in lst
def my_first(lst):
"""Returns the first element in the list"""
return ls... |
# -*- coding: utf-8 -*-
# 计算多个数乘积:
# 需要考虑没有乘积数的情况,抛出错误。
# TypeError:对类型无效的操作错误
# raise:自己抛出异常
# http://www.runoob.com/python/python-exceptions.html
def product(*xs ):
if len(xs) < 1:
raise TypeError('please input at least one param!')
product = 1
for x in xs:
product = product * x
return... |
class BankAccount:
def __init__(self, balance, username, pin):
self.balance = balance
self.username = username
self.pin = pin
self.disable = False
self.wrong_entries = 0
self.cooldown = 60
self.deposit_limit = 1000
def withdraw(self, amount):
if self.disable == False:
user_pin = int(input("PIN: ... |
import matplotlib.pyplot as plt
import itertools
import numpy as np
def plot_loss(train_model):
hist = train_model.history
acc = hist["acc"]
loss = hist["loss"]
val_loss = hist["val_loss"]
epochs = list(range(1, len(acc) + 1))
plt.plot(epochs, loss, "g--", label="Training Loss")
plt.plot(... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
#Sandro
import sqlite3
class ConexaoBD(object):
#inicializando o Banco de dados
def __init__( self, bdName ):
try:
#dfefinindo atributo conexao
self.conexao = sqlite3.connect(bdName)
#definindo atributo direcionador
... |
# Python 3.3.3 and 2.7.6
# python helloworld_python.py
from threading import Thread
sum = 0
def add():
global sum
for j in range(0,1000000):
sum += 1
def subtract():
global sum
for j in range(0,1000000):
sum -= 1
def main():
addThread = Thread(target = add, args = (),)
addThread.start()
subtractThre... |
import math
import operator
#CLASS START
class feed:
"""
GLOBAL VARIABLES:
training - Dict
testInstance - Dict
"""
def __init__(self, testInstance, training):
self.training = training
self.testInstance = testInstance
def euclideanDistance(self, trainingInstance, ... |
import pdb
tasks = [
{ "description": "Wash Dishes", "completed": False, "time_taken": 10 },
{ "description": "Clean Windows", "completed": False, "time_taken": 15 },
{ "description": "Make Dinner", "completed": True, "time_taken": 30 },
{ "description": "Feed Cat", "completed": False, "time_taken": 5 ... |
#https://www.hackerrank.com/challenges/python-lists/problem
N = int(input())
arr = []
for i in range(N):
inp = input().split()
if inp[0] == 'insert':
arr.insert(int(inp[1]), int(inp[2]))
elif inp[0] == 'print':
print(arr)
elif inp[0] == 'remove':
arr.remove(int(inp[1]))
... |
#print "Enter the number of inputs"
No_input = raw_input()
input = raw_input().split(' ')
sum = 0
for n in input:
sum = sum + long(n)
print sum
|
def reverse_word():
s = input("Enter a sentence containing multiple words: ").strip()
s = s.split()[::-1]
print(s)
s = " ".join(s)
return s
print(reverse_word())
|
def display_board(block):
print(" | | ")
print(block[7]+" | "+block[8]+" | "+block[9])
print(" | | ")
print("_______________")
print(" | | ")
print(block[4]+" | "+block[5]+" | "+block[6])
print(" | | ")
print("_______________")
print(... |
"""A video player class."""
from .video_library import VideoLibrary
import random
class VideoPlayer:
"""A class used to represent a Video Player."""
def __init__(self):
self._video_library = VideoLibrary()
def default_values(self):
global video_playing
glo... |
# Спринт 14
# H. Большое число
def compare(i1, i2):
if i1 + i2 > i2 + i1:
return True
return False
def insertion_sort(array):
for i in range(1, len(array)):
item = array[i]
j = i
while j > 0 and compare(item, array[j - 1]):
array[j] = array[j - 1]
j... |
#!/usr/bin/env python3
""" find duplicate files """
import argparse
import logging
import os
def find_duplicates(cmd_args):
""" find duplicates """
files_info = {}
for root, dirs, files in os.walk(cmd_args.dir):
logging.debug('Walking ... %s, %s, %s', root, dirs, files)
for file_name in ... |
"""
Given a string, find the length of the longest substring without repeating characters.
Example 1:
Input: "abcabcbb"
Output: 3
Explanation: The answer is "abc", with the length of 3.
Example 2:
Input: "bbbbb"
Output: 1
Explanation: The answer is "b", with the length of 1.
Example 3:
Input: "pwwkew"
Output: 3
Exp... |
"""
Calculator
Write a simple calculator that reads the three input lines: the first number, the second number and the operation, after which it applies the operation to the entered numbers ("first number" "operation" "second number") and outputs the result to the screen. Note that the numbers can be real.
Supported ... |
def knn(x_train, y_train, x_test, n_classes, device):
"""
x_train: 60000 x 784 matrix: each row is a flattened image of an MNIST digit
y_train: 60000 vector: label for x_train
x_test: 1000 x 784 testing images
n_classes: no. of classes in the classification task
device: pytorch device on which t... |
#!/usr/bin/env python
# Name: Sofie Löhr
# Student number: 11038926
"""
This script parses and processes the data from a csv file
"""
import csv
import pandas as pd
import numpy
import json
# Global constants
INPUT = "NFA_2018.csv"
OUTPUT_FILE = "data.json"
data_variable = "EFConsPerCap"
def processing(file):
"""
... |
l = int(input())
operacao = input()
soma = 0
for i in range(12):
for j in range(12):
valor = float(input())
if(i == l):
soma += valor
if(operacao == 'S'):
print("%.1f" %soma)
elif(operacao == 'M'):
print("%.1f" %(soma/12.0)) |
def contador_de_caracteres(s):
caracteres_ordenadas = sorted(s.lower())
caracter_anterior = caracteres_ordenadas[0]
contagem = 1
for caracter in caracteres_ordenadas[1:]:
if caracter==caracter_anterior:
contagem += 1
else:
print(f'{caracter_anterior}: {contagem}')... |
n = int(input('DIgite um numero '))
cont = 0
for c in range(1, n+1 ):
if n%c == 0:
print("O numero é divisivel por {}".format(c))
cont +=1
if cont > 2:
print("o numero {} não é primo".format(n))
else:
print("o numero {} é primo ".format(n))
|
def main():
num = int(input("Entre com um numero maior que 1: "))
soma = 0
for x in range(1,num+1):
if x % 5 == 0:
soma = soma + x
else:
continue
print(soma)
main() |
def main():
multiplicando = int(input("Entre com o multiplicando: "))
multiplicador = int(input("Entre com o multiplicador: "))
produto = 0
if multiplicador < 0 or multiplicando < 0:
print("Números negativos não podem ser usados")
else:
while multiplicador > 0:
produto = produto + multiplicando
multipli... |
def opcao(x):
if x > 20:
return "Va ao cinema!"
else:
return "Fique vendo TV"
def main():
x = float(input("Digite um numero: "))
print(opcao(x))
main() |
def main():
op = 1
soma = 0
while op != 0:
numero = int(input("Entre com um numero: "))
soma = soma + numero
op = int(input("Tecle 0 para parar ou qualquer valor para continuar: "))
print("Soma = ",soma)
main()
|
def inverte(x):
c = x//100
d = (x%100)//10
u = x % 10
udc = (u*100)+(d*10)+(c)
return udc
def main():
n = int(input("Entre com um numero de 3 algarismos: "))
inverso = inverte(n)
print("Inverso = ", inverso)
main() |
def soma_por_sub(x,y):
return (x+y)/(x-y)
def main():
x = float(input("Primeiro numero = "))
y = float(input("Segundo numero = "))
print("Resultado = ", soma_por_sub(x,y))
main() |
def antecessor(x):
return x - 1
def sucessor(x):
return x + 1
def main():
num = int(input("Entre com um numero = "))
print("Antecessor = ", antecessor(num))
print("Sucessor = ", sucessor(num))
main() |
def main():
maior = 0
numeros = []
for x in range(0,101):
numero = int(input("Digite 100 numeros: "))
numeros.append(numero)
'''while x < 10:
if numero[x] < numero[x+1]:
maior = numero[x+1]
else:
maior = numero[x]'''
print(max(numeros))
main() |
def main():
lista = []
i = 0
while i < 5:
n = int(input("Entre com uma sequencia de numeros: "))
lista.append(n)
i += 1
print(lista)
main()
|
""""
"""
pin = 1234
attmpt=3
x = 1
while x<=3:
inp=int(input("Enter PIN"))
if inp!=pin:
attmpt=attmpt-1
if attmpt ==0:
print("Blocked")
else:
print("Wrong! You have {}".format(attmpt))
x+=1
else:
print("Sucess")
break
# z=list(range(1,2... |
l1 = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
l2 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
resultList = []
for a in l1:
for b in l2:
if a == b:
shouldBeAdded = True
for c in resultList:
if c == a:
shouldBeAdded = False
break
... |
fruits = ['apple','orange','pear','banana','watermelon']
for fruit in fruits:
print(fruit) |
#!/usr/bin/env python3
# Created by: Liam Hearty
# Created on: Dec 2019
# This program uses a list as a parameter
import random
def biggest_number(list_of_numbers):
# this functions add up all the numbers in the list
total = 0
counter = 0
for counter in range(0, 9):
if list_of_numbers[0+co... |
import queue
import pandas as pd
class Refine:
def __init__(self, *args, **kwargs):
# threshold should be the first positional argument
self.threshold = args[0]
"""
"node": any node in the tree structure to start find the partitions of interest
"tree": if tree is passed i... |
import unittest
def calculate_levenshtein_distance(str1, str2):
if str1 and not str2:
return len(str1)
elif not str1 and str2:
return len(str2)
elif not str1 and not str2:
return 0
return calculate_levenshtein_distance_recursive(str1, str2, len(str1), len(str2))
de... |
def findSubsequence(arr):
# Write your code here
totalRecords = 0
distinct_set = []
min_removal_arr = []
distinct_set_count = 0
flag=False
for ele in arr:
totalRecords += 1
if ele not in distinct_set:
distinct_set += ele,
distinct_set_count += 1
... |
# https://www.geeksforgeeks.org/inorder-successor-in-binary-search-tree/
class TreeNode:
def __init__(self, data, left=None, right=None):
self.data = data
self.left = left
self.right = right
def inorder_traversal_recursive(self, root):
if not root:
return
... |
import re
def shoppingList(items):
#prices = list(map(float, re.findall(r'\d[0-9]*\.?\d+', items)))
matches = re.findall(r'\d[0-9]*\.?\d*', items)
print (matches)
prices = []
for match in matches:
if len(match) > 0:
prices.append(float(match))
print (prices)
ret... |
#!/usr/bin/env python
# coding: utf-8
# In[11]:
import pandas as pd
import numpy as np
def calculate_demographic_data(print_data=True):
df = pd.read_csv('adult.data.csv')
total_people = len(df)
def percentage(n):
return len(n)*100/total_people
gps = df.groupby('race')
races = ['Amer-Indian-... |
if __name__ == '__main__':
N = int(raw_input())
list = []
for _ in range(N):
line = raw_input().split()
command = line[0]
if command == "insert":
index1 = int(line[1])
index2 = int(line[2])
list.insert(index1, index2)
elif command == "appen... |
# Read an integer N. Without using any string methods, try to print the following: 123…N
from __future__ import print_function
if __name__ == '__main__':
n = int(input())
i = 1
while i <= n:
print(i, sep='', end='')
i += 1
# Let’s import the advanced print_function from the __future__ mo... |
if __name__ == '__main__':
n = int(input())
arr = map(int, input().split())
arr = sorted(arr, reverse=True)
for x in range(len(arr)):
if arr[x] != arr[x+1]:
print(arr[x+1])
break
x += 1
# Given the participants’ score sheet for your University Sports Day, you ar... |
print('''
1. Какое количество мужчин и женщин ехало на корабле? В качестве ответа приведите два числа через пробел.
2. Какой части пассажиров удалось выжить? Посчитайте долю выживших пассажиров. Ответ приведите в процентах (число в ин- тервале от 0 до 100, знак процента не нужен), округлив до двух знаков.
3. Какую до... |
def binary_search(v,x):
if x>v[-1]: return
start,end = 0,len(v)-1
while start<end:
mid = (start+end)//2
if v[mid]>=x:
end = mid
else:
start = mid+1
return start
|
class Instance:
properties = []
def __init__(self, a, t, n):
self.attributes = a
self.time = t
self.name = n
def __repr__(self):
return self.pretty_print(False)
def __str__(self):
return self.pretty_print(True)
def pretty_print(self, showAttributes=True):
printString = self.name+... |
def searchRange(nums, target):
l = 0
r = len(nums) - 1
while l <= r:
mid = (l + r) // 2
if nums[mid] == target:
l = mid
r = mid
while nums[l - 1] == target:
l = l - 1
while nums[r + 1] == target:
r = r + 1
return [l, r]
elif... |
def get_first(arr, target):
l, r = 0, len(arr) - 1
while l + 1 < r:
mid = l + (r - l) // 2
if arr[mid] == target:
r = mid # you want to find the first one, and move r towards the middle. if you were doing 'get_last' it would be 'l = mid'
elif arr[mid] < target:
l ... |
"""
需求:定义一个函数 sum_numbers,能够接收一个 num 的整数参数
计算 1 + 2 + ...
"""
def sum_numbers(num):
if num == 1:
return 1
# 假设 sum_numbers 能够完成 num - 1 的累加
temp = sum_numbers(num - 1)
# 函数内部的核心算法就是 两个数字的相加
return num + temp
print(sum_numbers(5))
|
# 转圈打印矩阵
# 【题目】 给定一个整型矩阵matrix,请按照转圈的方式打印它。 例如:1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
# 打印结果为:1,2,3,4,8,12,16,15,14,13,9, 5,6,7,11, 10
# 【要求】 额外空间复杂度为O(1)。
def printrectangle(matrix, leftrow, leftcol, rightrow, rightcol):
if leftrow == rightrow or leftcol == rightcol:
if leftrow == rightrow and leftcol ==... |
#Pam Fields
#ITEC 2905-01
#Lab 3: SQLite
import SQLite3
db = sqlite.connect('chainsawjugglerrecord.db') #Create a db for the data
cur = db.cursor() # Need a cursor object to perform operations
# Create a table
cur.execute('create table if not exists jugglers (name str, country str, catches int)')
#Add current jugg... |
# -*- coding: utf-8 -*-
"""
Created on Sun Feb 28 22:04:49 2021
@author: Jonas
"""
def iterPower(base, exp):
prod = 1
for i in range(1, exp + 1):
prod *= base * 1
return prod
print(iterPower(2, 4))
# for i in range(1, 3):
# print(i)
|
#You might need to process all the files that are in a specific directory or generate a directory with the results of your data analysis. As with files, Python provides a bunch of different functions that let us create, delete and browse the contents of directories.
#You might remember when we talked about the current... |
#In the last video, we wrote a script that processed a log file and extracted the names of each user who had started a cron job in the machine that we were investigating.
#This can be really helpful but there's more information that we might need. To improve our output, it would be a good idea to have a count of how ... |
#Up to now. We've seen how different programs can read from and write to standard IO streams and how the show environment can influence execution of a program. Yet another common way of providing information to our programs is through command line arguments.
#These are parameters that are passed to a program when it ... |
#If we want our Python scripts to manipulate the output of system command that we're executing, we need to tell the run function to capture it for us.
#This might be helpful when we need to extract information from a command and then use it for something else in our script. For example, say you wanted to create some ... |
def visokosny(year):
if year % 400 == 0:
return True;
elif year % 100 == 0:
return False;
elif year % 4 == 0:
return True;
else:
return False;
year = int(input("Введите год: "));
if (visokosny(year)):
print("Год високосный")
else:
print("Год не високосный") |
class Dineout:
class Discount:
def __init__(self, nbrFoods, price):
self.nbrFoods = nbrFoods
self.price = price
def __init__(self):
self.prices = {}
self.discounts = {}
self.foods = {}
def addDiscount(self, food, nbrOfFoods, price):
... |
# from threading import Thread
# from random import randint
# chegada = 20
# ranking = []
# class Lebre(Thread):
# def __init__(self, numero):
# Thread.__init__(self)
# self.quantidadePulos = 0
# self.distanciaPercorrida = 0
# self.numero = numero
# def run(self):
# w... |
# -*- coding: utf-8 -*-
"""
Created on Wed Jun 19 19:32:13 2019
@author: tomek
"""
# Program sprawdzający prawdopodobieństwo wygranaj w totka
# Simple app to check probability of winning in lottery
import random
class LottoDraw:
def __init_(self, draws_qty = 1000, lottery_no_range = 49, no_of_numbers = 6):
... |
#!/usr/bin/env python3
class StackUnderFlow(Exception):
pass
class Stack:
def __init__(self, size):
self.size = size
self.stack = [0] * size
self.top = 0
def push(self, data):
if self.top == self.size - 1:
self.stack[top] = data
self.top += 1
... |
#!/usr/bin/env python3
from nodes import Leaf
class Tree:
def __init__(self):
self.root = None
def __append(self, data):
leaf = Leaf(data)
branch = self.root
if self.root == None:
self.root = leaf
else:
while branch:
if leaf.dat... |
import pandas as pd
inputFile = 'Data/trainNoZeroWithWeekdayIsHoliday.csv'
keyFile = 'Data/key.csv'
weatherFile = 'Data/weather.csv'
outputFile = 'Data/dataWithStation.csv'
inputData = pd.read_csv(inputFile)
keyData = pd.read_csv(keyFile)
weatherData = pd.read_csv(weatherFile)
inputData.insert(5, 'station_nbr', 0)
#... |
'''
Input: a List of integers
Returns: a List of integers
'''
def moving_zeroes(arr):
# Your code here
non_zero_pointer = 0
zero_pointer = len(arr) - 1
while non_zero_pointer < zero_pointer:
while arr[non_zero_pointer] != 0 and non_zero_pointer < zero_pointer:
non_zero_pointer += 1
... |
import csv
with open('mycsv.csv', 'w', newline='') as f: #'w' stands for WRITE
theWriter = csv.writer(f)
theWriter.writerow(['col1','col2','col3'])
for i in range (5):
theWriter.writerow(['one','two','three'])
|
# Copyright 2000 by Jeffrey Chang. All rights reserved.
# This code is part of the Biopython distribution and governed by its
# license. Please see the LICENSE file that should have been included
# as part of this package.
"""This provides useful general math tools.
Functions:
fcmp Compare two floatin... |
# Copyright 2000 by Jeffrey Chang. All rights reserved.
# This code is part of the Biopython distribution and governed by its
# license. Please see the LICENSE file that should have been included
# as part of this package.
"""This provides useful general functions for working with lists.
Functions:
asdict ... |
#!/bin/python3
import sys
def reduce(fives, threes):
fives = fives[:-1]
threes += "3"
return fives, threes
def main(n):
fives = ""
threes = ""
for i in range(n):
fives += "5"
if not len(fives)%3:
return fives
else:
fives, threes = reduce(five... |
"""
Complete all of the TODO directions
The number next to the TODO represents the chapter
and section that explain the required code
Your file should compile error free
Submit your completed file
"""
# TODO 7.2 Lists
# Create a list of days of the week, assign it to the variable days, remove """ "... |
"""
Complete all of the TODO directions
The number next to the TODO represents the chapter
and section that explain the required code
Your file should compile error free
Submit your completed file
"""
# TODO 5.2 - calling an existing function
# beneath the following function, write the code to call... |
"""
Convex Hull Assignment: COSC262 (2018)
Student Name: Harrison Cook
Usercode: HGC25
"""
def readDataPts(filename, N):
"""Reads the first N lines of data from the input file
and returns a list of N tuples
[(x0,y0), (x1, y1), ...]
"""
listPts = []
file = open(filename, "r"... |
def adjacency_list(graph_str):
"""Turns a textual representation of a graph into an adjcency list"""
graph = graph_str.splitlines()
info = graph.pop(0)
info = info.split()
output_list = []
for i in range(int(info[1])):
output_list.append([])
try:
info[2]
if info[0] ==... |
#!/usr/bin/python
def minmax(test, *args):
res = args[0]
for arg in args[1:]:
if test(arg, res):
res = arg
return res
def lessthan(x, y): return x < y
def grtthan(x, y):return x > y
print(minmax(lessthan, 4, 2, 1, 5, 6,3))
print(minmax(grtthan, 4, 2, 1, 5, 6,3))
|
import unittest
from LoginComponent.user import User
class test_user(unittest.TestCase):
""" Unittests for the user class """
def setUp(self):
self.user = User("testuser", "secretpass")
self.hasheduser = User("testuser", "secretpass", True)
# Create tests.
def test_user_constructor_u... |
##################################################
# FILE: ex10.py
# WRITER : yevgeni, jenia90, 320884216
# EXERCISE : intro2cs ex10 2015-2016
# DESCRIPTION : WikiNetwork basic implementation exercise
#
##################################################
def read_article_links(file_name='links.txt'):
"""
R... |
###############################################################################
# FILE: asteroid.py #
# WRITERS: Yevgeni Dysin, jenia90, 320884216; Ben Faingold, ben_f, 208482604 #
# EXERCISE: intro2cs ex9 2015-2016 #
... |
import numpy as np
from numpy import linalg as la
np.set_printoptions(precision=3)
class DiGraph:
"""A class for representing directed graphs via their adjacency matrices.
Attributes:
A_hat
"""
# Problem 1
def __init__(self, A, labels=None):
"""Modify A so that there are no sin... |
# Given an array of integers that is already sorted in ascending order, find two numbers such that the add upto a specific target numbers
#
# Example : [3,5,8,10,15,21]
# Sum: 23
# Number: 8 + 15
numbers = [3,5,8,10,15,21]
sum = 15
class sumOf2Numbers(object):
def sumOf2(self, numberList, sum):
if len(nu... |
names = ['Fred', 'Wilma', 'Barney', 'Ivan', 'Francisco']
def long_name(name):
return len(name) > 5
print(list(filter(long_name, names)))
# Out: ['Barney']
[name for name in names if len(name) > 5] # equivalent list comprehension
# Out: ['Barney']
|
# BAD create a concatenated string from 0 to 19 (e.g. "012..1819")
nums = ""
for n in range(20):
nums += str(n) # slow and inefficient
print(nums)
# BETTER create a concatenated string from 0 to 19 (e.g. "012..1819")
nums = []
for n in range(20):
nums.append(str(n))
print("".join(nums)) # much more efficien... |
import math
pow(2, 3)
# To check the built in function in python we can use dir()
# print(dir(__builtins__), "\n")
# To know the functionality of any function
help(pow)
math.sqrt(16)
# To know all the functions in a module
# print(dir(math), "\n")
# __doc__ is useful to provide some documentation
print(math.__doc__)... |
def revword(word):
word = word.lower()
return word[::-1]
def countword():
fname = 'text.txt'
fh = open(fname, "r")
first_word = fh.read()
first_word = first_word.split()[0].lower()
count = 1
with open(fname, 'r') as a_file:
for line in a_file:
if line.startswith(fir... |
"""
Задание 2 (№70).
Миша заполнял таблицу истинности функции (x ∨ ¬y) ∧ ¬(y≡z) ∧ w,
но успел заполнить лишь фрагмент из трёх различных её строк,
даже не указав, какому столбцу таблицы соответствует каждая из переменных.
"""
print('x y z w F')
r = 0, 1
for x in r:
for y in r:
for z in r:
for w i... |
"""
(№ 169) Запишите число, которое будет напечатано в результате выполнения следующей программы.
"""
s = 0
k = 0
while s < 1024:
s = s + 10
k = k + 1
print(k)
|
N = int(input())
f = [0] * (N + 1) # Будем игнорировать число с нулевым индексом
f[1] = f[2] = 1 # Мы знаем, что это будут первые две единицы
for i in range(3, N + 1):
f[i] = f[i - 1] + f[i - 2] # Рекуррентная формула
print(f[N])
|
# Задание 2 (№1357).
print('x y z w F')
k = 0, 1
for a in k:
for b in k:
for c in k:
for d in k:
# F = ((a and b) == not(c)) and (not(b) or d)
# print(F)
pass
|
"""
Вася составляет 4-буквенные коды из букв У, Л, Е, Й. Каждую букву нужно использовать ровно 1 раз,
при этом код не может начинаться с буквы Й и не может содержать сочетания ЕУ.
Сколько различных кодов может составить Вася?
"""
from itertools import product
p = product('УЛЕЙ', repeat=4)
s = map(lambda x: "".join(x),... |
n = int(input())
count = 0
maxdigit = 0
summa = 0
while n != 0:
digit = n % 10
if digit > maxdigit:
maxdigit = digit
if digit % 2 != 0:
summa += digit
n = n//10
# print('Max Digit =', maxdigit)
# print('Length even numbers =', count)
print('Summa odd elements', summa)
|
"""
Укажите наименьшее возможное значение x,
при вводе которого программа выведет число 12
"""
x = int(input())
a = 0
b = 10
while x > 0:
d = x % 6
if d > a: a = d
if d < b: b = d
x = x // 6
print(a * b)
print('---')
answer = 0
answers = []
answer_t = 12
while answer < 200:
x = answer
a = 0
... |
start, end = 2948, 20194
def isPrime( x ):
if x <= 1: return False
d = 2
while d*d <= x:
if x % d == 0:
return False
d += 1
return True
for x in range( end, start-1, -1 ):
if isPrime(x):
print(x)
break
|
"""
Сначала 5, потом 12. Сколько существует трёхзначных X?
"""
# x = int(input())
# a = 0
# b = 1
# while x > 0:
# if x % 2 > 0:
# a += x % 11
# else:
# b *= x % 11
# x //= 11
# print(a)
# print(b)
# print('---')
x = 100
answers = []
answer_a = 5
answer_b = 12
while x < 1000:
number = ... |
"""
Маша составляет 5-буквенные коды из букв В, У, А, Л, Ь. Каждую букву нужно использовать ровно 1 раз,
при этом код буква Ь не может стоять на первом месте и перед гласной. Сколько различных кодов может составить Маша?
"""
from itertools import product
p = product('ВУАЛЬ', repeat=5)
s = map(lambda x: "".join(x), p)
... |
"""
F(n) = 2, при n = 1
F(n) = F(n-1) + 5n^2, если n > 1
Чему равно значение функции F(39)?
"""
def F(n):
if n > 1:
return F(n-1) + 5 * n**2
else:
return 2
print(F(39)) # 102697
# Совпало с Excel'ем
|
"""
---
Р-20 (М.В. Кузнецова).
Обозначим через ДЕЛ(n, m) утверждение «натуральное число n делится без остатка
на натуральное число m». Для какого наименьшего натурального числа А формула
ДЕЛ(x, А) → ((ДЕЛ(x, 21) + ДЕЛ(x, 35))
тождественно истинна
(то есть принимает значение 1 при любом натуральном значении переменной х... |
"""
Задание 23 (№678).
Исполнитель Калькулятор преобразует число на экране. У исполнителя есть три команды, которым присвоены номера:
1. Прибавить 1
2. Умножить на 3
3. Умножить на 4
Сколько существует программ, для которых при исходном числе 2 результатом является число 60
и при этом траектория вычислений содержит чис... |
"""
Рассматривается множество целых чисел, принадлежащих числовому отрезку [9999; 99999],
которые кратны сумме своих цифр. Найдите количество таких чисел и максимальное из них.
В ответе запишите два целых числа: сначала количество, затем – максимальное число.
Для выполнения этого задания можно написать программу или ... |
# Алгоритм Евклида - находим общий делитель
number1 = int(input())
number2 = int(input())
while number1 != number2:
if number1 > number2:
number1 = number1 - number2
else:
number2 -= number1
print(number1)
|
"""
Как я понял, здесь надо найти наименьшее четное среди всего документа. Нашёл. Ответ сошёлся: 888.
29.11.2020
"""
document = open('24_321.txt')
a = document.read()
current_number = ''
b = []
result = 999999
for i in range(len(a)):
if a[i].isdigit():
current_number += a[i]
else:
if current_n... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.