text stringlengths 37 1.41M |
|---|
from abc import ABC, abstractmethod
class MAB(ABC):
"""
Abstract class that represents a multi-armed bandit (MAB)
"""
@abstractmethod
def play(self, tround, context):
"""
Play a round
Arguments
=========
tround : int
positive integer... |
from random import randint
def contarDigitosPares(numero):
pares=0
list2=[]
for i in numero:
pares=0
for k in range(i-1):
if (k%2==0):
pares = pares + 1
else:
pares = pares+0
list2.append(pares)
return list2 ... |
import numpy as np
import sys
class DType:
"""
Instances of `DType` represent the kind and size of data elements.
The data type of a `Tensor` can be obtained via `phi.math.Tensor.dtype`.
The following kinds of data types are supported:
* `float` with 32 / 64 bits
* `complex` with 64 / 128 bi... |
# Author: Abhi Patel
# Date: 12/25/17
# Purpose: To implement an algorithm of Arnold's Cat Map.
import cv2
import numpy as np
def run():
img = cv2.imread('img/dexter.png')
for i in range (1,26):
img = transform(img, i)
def transform(img, num):
rows, cols, ch = img.shape
if... |
import numpy as np
N=int(input())
marksheets=[]
names=[]
for i in range(0,N):
# name=input()
marks=float(input())
marksheets.append(marks)
# print(marksheets)
marksheets_array=np.array(marksheets)
# print(np.unique(marksheets_array))
sorted_array=np.sort(marksheets_array)
print(sorted_array[1])
'''
n = in... |
# Python program to swap two variables
x = 5
y = 10
# To take inputs from the user
#x = input('Enter value of x: ')
#y = input('Enter value of y: ')
# create a temporary variable and swap the values
temp = x
x = y
y = temp
print('The value of x after swapping: {}'.format(x))
print('The value of y after swapping: {}... |
#age 18-60
entires=int(raw_input("number of entires:"))
file_out = open("details.csv","w")
header = "name,age,salary\n"
file_out.write(header)
for x in range(entires):
name=raw_input("enter name:")
age=int(raw_input("enter age:"))
if age>60 or age<18:
print "please enter valid age."
... |
import sys
def add(no1,no2):
return no1+no2
no1 = int(sys.argv[1])
no2 = int(sys.argv[2])
sum = add(no1,no2)
print "The sum: ",sum |
"""year=2017
if (year%4)==0:
print "leaf year".format(year)
else:
print "no leaf year ".format(year)
"""
import sys
year=int(sys.argv[1])
if year%4==0:
print "leaf year"
else:
print "not leaf year"
|
l = [1,2,3,1,2,"rama","rama"]
print l
l1 = set(l)
print l1
for i in l1:
print i
new_l = list(l1)
print new_l
print "Types"
print type(l)
print type(l1)
print type(new_l)
print type(100)
print type("Ram") |
class Cal:
def __init__(self,x,y):
self.x=x
self.y=y
def add(self):
return self.x+self.y
def mul(self):
return self.x*self.y
obj=Cal(10,20)
add=obj.add()
mul=obj.mul()
print add,mul
class Cal1(Cal):
def sub(self):
return self.x-self.y
def div(self):
r... |
time="30"
y=time.split(":")
if len(y)==3:
hr=int(y[0])*60*60
min = int(y[1]) * 60
elif len(y)==2:
hr=0
min = int(y[1]) * 60
else:
hr=0
min=0
sec=int(y[-1])
t=hr+min+sec
print t
|
import os,tarfile, glob
import shutil
string_to_search=input("Enter the string you want to search : ")
all_files = [f for f in os.listdir('.') if os.path.isfile(f)] #all_files holds all the files in current directory
for current_file in all_files:
if (current_file.endswith(".tgz")) or (current_file.endswith("tar.gz... |
import os, glob
string_to_search=input("Enter the string you want to search : ")
path='nvram2\logs\*.txt'
files=glob.glob(path)
for current_file in files:
with open(current_file) as f2:
for line in f2:
if string_to_search in line:
print(current_file) #print file name which contains the string
print(str(... |
class Solution:
# 全排列
def permute(self, nums: List[int]) -> List[List[int]]:
res = []
if not nums:
return res
else:
self.fun(arr=[], others=nums, res=res)
return res
def fun(self, arr, others, res):
... |
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def isSymmetric(self, root: TreeNode) -> bool:
'''
两个孩子树同时进行镜像比较
'''
def isMirror(left, right... |
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def reorderList(self, head: ListNode) -> None:
"""
Do not return anything, modify head in-place instead.
"""
#对于链表,分成前后两部分
#对... |
# Python program to insert into a sorted linked list
class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def sortedInsert(self, new_node):
if self.head is None:
new_node.next = self.head
self.head = new_node
elif self.hea... |
print("Enter the values:" )
value_1=input("value 1: ")
value_2=input("value 2: ")
value_3=input("value 3: ")
list1=[value_1,value_2,value_3]
list1.sort()
median=list1[1]
print(median)
|
'''Pre-2018 Template
Before 2018, solutions were submitted in text files with the extention `.out`.
Download the approprite input files from the problem description and put them
in the problem folder, then change the FILENAME variable appropriately.
'''
FILENAME = "tests"
def main():
with open(FILENAME + ".in") as ... |
class SkipIterator:
def __init__(self, iterator):
self.iterator = iterator
self.skip = {}
self.cursor = None
self.seekCursor() # holds value which would be returned in next subsequent call
def hasNext(self):
return self.cursor!=None
#Time Complexity: O(1)
#Time Complexity: O(1)
def ... |
from steganography.steganography import Steganography
from datetime import (datetime)
from new import add_status # from new file import the add_status function
from userdetail import Spy,chatmessage,spy,user_friend
friends=["juhi","davi","savita","jyoti","sudiksha","anu","swati"]# list of friends
def add_friend(): #... |
import pygame
import gamemode
class AttractMode(gamemode.GameMode):
""" Attract Mode - get the player excited to play our game """
def __init__(self, screen, game, message="Street Chase"):
super().__init__(screen, game, message) # calls constructor of base class
#1
self.name = "AttractMode"
... |
"""
Python 3 solution to the Exercism exercise 'largest-series-product'
"""
from functools import reduce
def largest_product(series, size):
"""
return the largest product of `size` consecutive digits fron `series`
"""
if size < 0:
raise ValueError
def product(digits):
"""
... |
"""
Python 3 solution to the Exercism 'series' exercise
"""
def slices(series, length):
"""
return the 'set' of length n 'substrings'
The tests cases require a list of lists of integers.
"""
result = []
if len(series) < length or length < 1:
raise ValueError
while len(series) ... |
"""
Python 3 solution to the Exercism 'rotational cypher' exercise
"""
LOWER_ALPHA = "abcdefghijklmnopqrstuvwxyz"
UPPER_ALPHA = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
def rotate(text, key):
"""
return text encrypted using key and the rotational cypher method
"""
key = key % 26
lower = LOWER_ALPHA[key:]... |
#!/usr/bin/python3
"""
an example of recursive programming
Provides a script/function to calculate terms of the Fibonacci series.
This example of the power of recursion has log(n) time complexity.
It takes advantage of the identities:
F(2n-1) = F(n) * F(n) + F(n-1) * F(n-1)
F(2n) = (2 * F(n-1) + F(n)) * F(n)... |
L = [1, 1, 1, 1, 4]
n = 2
def getSublists(L, n):
megaList = []
while len(L) > 0:
if len(L[:n]) < (n // 2):
sub = sub[:(n // 2)] + L[:n]
else:
sub = L[:n]
megaList.append(sub)
del L[:n]
return megaList
print(getSublists(L, n))
|
x = 24
ab = abs(x)
epsilon = .01
numGuesses = 0
isNeg = False
low = 0.0
high = max(1.0, ab)
ans = (high+low)/2.0
while abs(ans**2 - ab) > epsilon:
numGuesses += 1
if ans**2 < ab:
low = ans
else:
high = ans
ans = (high+low)/2.0
if x < 0:
print('numGuesses =', str(numGuesses))
pr... |
d=int(input())
ti=0
fot=d
while(fot>0):
fet=fot%10
ti=ti+(fet**3)
fot=fot//10
if(d==ti):
print("yes")
else:
print("no")
|
# Autor: Rubén Villalpando Bremont, A01376331, grupo 4
# Descripcion: Programa que le pregunta al usuario la velocidad a la que viaja un auto y le devuelve unos datos específicos.
# Escribe tu programa después de esta línea
velocidad = int(input("Escriba la velocidad a la que va un vehículo en km/h: "))
distancia_7hor... |
# 3. Put a # (octothorpe) character at the beginning of a line. What did it do? Try to find out what this character does.
#print("Hello World!")
print("Hello Again")
print("I like typing this.")
print("This is fun.")
print('Yay! Printing.')
print("I'd much rather you 'not'.")
print('I "said" do not touch this.')
# The... |
cat = "cat"
tabby_cat = "\tI'm tabbed in."
persian_cat = "I'm split\non a line."
backslash_cat = f"I'm \\ a \\ {cat}."
fat_cat = """
I'll do a list:
\t* {} food
\t* Fishies
\t* {}nip\n\t* Grass
"""
print(tabby_cat)
print(persian_cat)
print(backslash_cat)
print(fat_cat.format(cat, cat))
print('A \'single\' quote in a... |
my_set = {1,3,5}
my_dict ={'name':'Jose', 'age':90, 'grades':[13, 45, 66, 23, 22]}
another_dict {1:15, 2:75, 3:150}
#dictionary
horse = {
'name': 'Tuffy',
'age': '24'
}
lottery_player = [
{
'name': 'Rolf',
'numbers': (13, 45, 66, 23, 22)
},
{
'name': 'James',
'numbe... |
class Persona:
def __init__(self, nombre):
self.nombre = nombre
def anvanza(self):
print('Ando caminando')
class Ciclista(Persona):
def __init__(self, nombre):
super().__init__(nombre)
def anvanza(self):
print('Ando pedaleando')
class Nadador(Persona):
def... |
#!/usr/bin/env python3
def security_tax():
global social_security
global income_tax
global after_tax
global after_tax1
social_security = salary1*(0.08+0.02+0.005+0+0+0.06)
if salary1 <= 3500:
after_tax = salary1 - social_security
elif salary1 > 3500:
taxable = salary1 - soc... |
# AUTHOR: GILBERT
# this class is a child class of the parent class called Task
# contains the objects and instance variable of the sub task a user
# might want to enter
from Task_class import *
class Sub_task(Task):
# define init function that takes in arguments
def __init__(self, my_date,task_name, location... |
# -*- coding: utf-8 -*-
def odd_val(n=100):
a = 0;
while a<=n:
if a % 2 == 0:
print(a,end=", ")
a += 1
odd_val()
print('')
odd_val(10)
print('')
odd_val() |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Jan 9 17:20:32 2017
@author: mindovermiles262
Codecademy Python
Define a new class named "Car". For now, since we have to put something
inside the class, use the pass keyword.
"""
class Car(object):
pass |
# -*- coding: utf-8 -*-
"""
Created on Wed Jan 11 07:14:09 2017
@author: mindovermiles262
Codecademy Python
Set the variable my_variable equal to the value 10.
Click the Save & Submit button to run your code
"""
# Write your code below!
my_variable = 10 |
# -*- coding: utf-8 -*-
"""
Created on Wed Jan 11 07:27:40 2017
@author: mindovermiles262
Codecademy Python
Assign the variable total to the sum of meal + meal * tip on line 8. Now you
have the total cost of your meal!
"""
# Assign the variable total on line 8!
meal = 44.50
tax = 0.0675
tip = 0.15
meal = meal +... |
# -*- coding: utf-8 -*-
"""
Created on Fri Jan 6 09:39:29 2017
@author: mindovermiles262
Codecademy Python
In the example above, we define a function called first_item. It has one
argument called items.
Inside the function, we print out the item stored at index zero of items.
After the function, we create a new li... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Jan 7 19:09:56 2017
@author: mindovermiles262
Codecademy Python
Define a function called flip_bit that takes the inputs (number, n).
Flip the nth bit (with the ones bit being the first bit) and store it in result.
Return the result of calling bin(res... |
# -*- coding: utf-8 -*-
"""
Created on Fri Jan 6 09:14:28 2017
@author: mindovermiles262
Codecademy Python
On line 18, define a new function called grades_variance() that accepts one
argument, scores, a list.
First, create a variable average and store the result of calling
grades_average(scores).
Next, create ano... |
# -*- coding: utf-8 -*-
"""
Created on Fri Jan 6 09:37:45 2017
@author: mindovermiles262
Codecademy Python
Define a function called add_function that has 2 parameters x and y and
adds them together.
"""
m = 5
n = 13
# Add add_function here!
def add_function(x, y):
return x + y
print(add_function(m, n)) |
# -*- coding: utf-8 -*-
"""
Created on Tue Jan 10 08:50:06 2017
@author: mindovermiles262
Codecademy Python
Iterate over my_list to get each value
Use my_file.write() to write each value to output.txt
Make sure to call str() on the iterating data so .write() will accept it
Make sure to add a newline ("\n") after eac... |
# -*- coding: utf-8 -*-
"""
Created on Fri Jan 6 09:13:20 2017
@author: mindovermiles262
Codecademy Python
Define a function grades_average(), below the grades_sum() function that does
the following:
Has one argument, grades, a list
Calls grades_sum with grades
Computes the average of the grades by dividing that ... |
# -*- coding: utf-8 -*-
"""
Created on Wed Jan 11 08:37:56 2017
@author: mindovermiles262
Codecademy Python
This time we'll give the expected result, and you'll use some combination of boolean operators to achieve that result.
Remember, the boolean operators are and, or, and not. Use each one at least once!
"""
#... |
# -*- coding: utf-8 -*-
"""
Created on Wed Jan 11 07:44:08 2017
@author: mindovermiles262
Codecademy Python
Create a new variable brian and assign it the string "Hello life!".
"""
# Set the variable brian on line 3!
brian = "Hello life!" |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Jan 9 17:34:21 2017
@author: mindovermiles262
Codecademy Python
Inside the Car class, add a method named display_car() to Car that will
reference the Car's member variables to return the string, "This is a [color]
[model] with [mpg] MPG." You can u... |
# -*- coding: utf-8 -*-
"""
Created on Wed Jan 4 12:35:20 2017
@author: mindovermiles262
Define a function called anti_vowel that takes one string, text, as input and returns the text with all of the vowels removed.
For example: anti_vowel("Hey You!") should return "Hy Y!".
Don't count Y as a vowel.
Make sure to r... |
# -*- coding: utf-8 -*-
"""
Created on Wed Jan 11 08:49:39 2017
@author: mindovermiles262
Codecademy Python
Use and to add a second condition to your if statement. In addition to your
existing check that the string contains characters, you should also
use .isalpha() to make sure that it only contains letters.
Don... |
# -*- coding: utf-8 -*-
"""
Created on Fri Jan 6 10:03:12 2017
@author: mindovermiles262
Codecademy Python
Use the print command to display the contents of the board list.
"""
board = []
#initalize board
for i in range(0,5):
board.append(["O"] * 5)
print(board) |
# -*- coding: utf-8 -*-
"""
Created on Fri Jan 6 09:11:16 2017
@author: mindovermiles262
Codecademy Python
Define a function on line 3 called print_grades() with one argument, a list
called grades.
Inside the function, iterate through grades and print each item on its own
line.
After your function, call print_gra... |
# -*- coding: utf-8 -*-
"""
Created on Fri Jan 6 09:33:55 2017
@author: mindovermiles262
Codecademy Python
Append the number 4 to the end of the list n.
"""
n = [1, 3, 5]
# Append the number 4 here
n.append(4)
print (n) |
# -*- coding: utf-8 -*-
"""
Created on Wed Jan 4 12:29:36 2017
@author: mindovermiles262
Write a function called digit_sum that takes a positive integer n as input and
returns the sum of all that number's digits.
For example: digit_sum(1234) should return 10 which is 1 + 2 + 3 + 4.
(Assume that the number you are... |
# -*- coding: utf-8 -*-
"""
Created on Wed Jan 11 07:16:26 2017
@author: mindovermiles262
Codecademy Python
Try it and see! Change the value of my_int from 7 to 3 in the editor
"""
# my_int is set to 7 below. What do you think
# will happen if we reset it to 3 and print the result?
my_int = 7
# Change the value ... |
from IPython.display import clear_output
import random
# this function prints grid and all instances of objects
def makeGrid(rows, cols, monsters, player, egg, door):
for y in range(rows):
print(' ---'*cols)
for x in range(cols):
monster_created = False
for monster in monste... |
# This class provides methonds for filling in data between known [x,y] points using linear interpolation.
# method interp_x returns an [x,y] point at a desired x which lies between two given [x,y] points
# method interp_nSpaced returns a list of n number of [x,y] points that are evenly spaced between two given [x,y]... |
from copy import copy
class Human:
def __init__(self, first, last, age):
self.first = first
self.last = last
self.age = age
def __repr__(self):
return f"Human named {self.first} {self.last} aged {self.age}"
def __len__(self):
# len() function will return age of an object
return self.age
def __add_... |
import re
text = "Last night Mrs. Daisy and Mr. white murdered Ms. Chow"
regex = r'(Mr.|Mrs.|Ms.) ([a-z])[a-z]+'
#Using sub method on Regular Expression Object
# pattern = re.compile(regex, re.I)
# result = pattern.sub("\g<1> \g<2>", text)
#Using sub method on re module
result = re.sub(regex, "\g<1> \g<2>", text, fla... |
cards_arr = [w[0] for w in list(input().split(' '))]
strength = 1
# count occurance of every card in the list
for i in range(5):
same_cards = cards_arr.count(cards_arr[i])
strength = same_cards if same_cards > strength else strength
print(strength) |
import csv
from tweet import Tweet
tweets = []
top_count = 10
filename = 'tweet_activity_metrics.csv'
def main():
with open(filename, 'rb') as csvfile:
csvfile.readline()
reader = csv.reader(csvfile)
for row in reader:
t = Tweet( row[0], row[1], row[2], row[3], row[4], row[5], row[6], int(ro... |
class Argument(object):
""" This is a class for passing arguments
"""
def __init__(self):
self.arglist = {} # empty dict
def insert(self, argname):
""" insert an argname with no argval (True)
"""
self.insert(argname, True)
def insert(self, argname, argval):
... |
'''
Alessia Pizzoccheri
Wholesale
Test Case #1
3 pies crusts, 4 potatoes, 3 packages of meat, 1 pack of corn
Test Case #2
1 pies crusts, 23 potatoes, 5 packages of meat, 2 pack of corn
Test Case #3
5 pies crusts, 42 potatoes, 5 packages of meat, 8 pack of corn
Test Case #4
2 pies crusts, 6 potatoes,... |
'''
Alessia Pizzoccheri - CS 5001 02
Haversine function parameters
distance = haversine(latitude1, longitude1, latitude2, longitude2)
Test Case #1
Boston
Test Case #2
Miami
Test Case #3
Seattle, 47.6062, 122.3321
7118.43 nautical miles
'''
from haversine import haversine
d... |
##########################
# object oriented programming
##########################
# programming paradigm based on the concept of objects
# objects = data structures containing data (or attributes) and methods (or procedures)
# create your own data types -> object definitions known as classes
# class = definition of... |
# fruits.txt is in same directory as fileprocessing
myfile = open("fruits.txt")
print(myfile.read()) # this is a read method
# another way to do it
file = open("bear.txt")
content = file.read()
print(content)
# close files
myfile2 = open("fruits.txt")
content2 = myfile2.read() #store in variable
myfile2.... |
def is_prime(x):
for i in range(2, x):
if x % i == 0:
return False
return True
#--------main---------
while True:
n = eval(input('n='))
for n1 in range(n, 1, -1):
if is_prime(n1):
Max = n1
break
if Max == n1:
print('biggest',Max)
nlist ... |
class library:
Booker={}
List_of_Books=[]
def __init__(self,Books1,library_name):
for i in list(Books1):
self.Books=library.List_of_Books.append(i)
self.library=library_name
def Display(self):
print("List Of Books in our library:")
for i in enumerate(library.... |
def large_x_one(numbers, n):
digits = list(str(numbers))
result = 0
digits.reverse()
for i, digit in enumerate(digits):
result += n*int(digit)*10**i
return result
def multiply_large_number(num1, num2):
num2_digits = list(str(num2))
result = 0
num2_digits.reverse()
for i, ... |
import numpy as np
'''
* Execution of this function happens in 3 steps
* 1) We choose a random pivot
* 2) We put the array into a set less than the pivot
* and a set greater than the pivot
* 3)
'''
def quicksort(arr=None):
if arr is None:
# If no array is passed, initialize a random array
arr = np.random.... |
# Crie uma função que recebe como parâmetros dois valores e retorna o menor valor
def menor_valor(valor1, valor2):
if (valor1 < valor2):
return valor1
else:
return valor2
entrada_1 = int(input('digite um valor '))
entrada_2 = int(input('digite um valor '))
print('O menor valor digitado foi ... |
# Elaborar um programa que efetue a leitura de três valores inteiros (variáveis A, B, C)
# e apresente como resultado final o valor do quadrado da soma
var_A = int(input('Digite o primeiro valor '))
var_B = int(input('Digite o primeiro valor '))
var_C = int(input('Digite o primeiro valor '))
soma = var_A + var_B + va... |
def signos(dia, mes):
JANEIRO = 1
FEVEREIRO = 2
MARCO = 3
ABRIL = 4
MAIO = 5
JUNHO = 6
JULHO = 7
AGOSTO = 8
SETEMBRO = 9
OUTUBRO = 10
NOVEMBRO = 11
DEZEMBRO = 12
if(dia >= 21 and mes == MARCO) or (dia <= 20 and mes == ABRIL):
return 'Aries'
elif(dia >= 2... |
# Elaborar um programa que efetue a leitura de quatro valores inteiros (variáveis A, B, C e D).
# Ao final o programa deve apresentar o resultado do produto (variável P) do primeiro com o terceiro valor,
# e o resultado da soma (variável S) do segundo com o quarto
var_A = int(input('Digite o primeiro valor '))
var_B =... |
def palindrome(n):
n = str(n)
i = 0
res = True
while i<((len(n))/2):
if n[i] != n[-(i+1)]:
return False
i += 1
return
print(palindrome(1000021))
|
def word_jumble():
scrambled_word = raw_input('Enter a word to scramble: ')
matching_words = []
scrambled_word_length = len(scrambled_word)
dictionary = import_dictionary('dictionary.txt')
dictionary.sort(key = len)
for word in dictionary:
if len(word) > scrambled_word_length:
if scrambled_word in... |
# parses text-wiki format and outputs each word at separate line
# input has a wiki article per line: "title tab string-escaped article content"
import string
import sys
for line in sys.stdin:
line = line.split("\t")[1].decode("string-escape").lower().replace("\n","").replace("."," ").split()
for word in line:
... |
class Ttype(object):
def displayNumType(num):
print num,'is',
if isinstance(num, (int, float,long,complex)):
print 'a number of type:',type(num).__name__
else:
print 'not a number at all!!'
|
class Person():
def __init__(self,name):
self.name=name
def Sayhello(self):
print "hello,my name is",self.name
def __del__(self):
print "%s says bye",self.name
|
class myDecorator(object):
def __init__(self, f):
print "inside myDecorator.__init__()"
def f(self,name):
self.name=name
return self.name # Prove that function definition has completed
def __call__(self):
print "inside myDecorator.__call__()"
@myDecorator
def aFunction():
print "inside aFunction()"
pri... |
a = []
a = input("Enter a string for processing")
print "maximum of the string is",max(a)
print "minimum of the string is",min(a)
print "length of the string is",len(a)
|
'''
Условие
Условие
Дана строка. Если в этой строке буква f встречается только один раз,
выведите её индекс. Если она встречается два и более раз, выведите
индекс её первого и последнего появления. Если буква f в данной
строке не встречается, ничего не выводите.
При решении этой задачи не стоит использовать циклы.
'... |
'''
Условие
Дана строка, в которой буква h встречается как минимум два раза.
Разверните последовательность символов, заключенную между первым
и последним появлением буквы h, в противоположном поря
'''
#**************************************************
s =input()
start=s.find('h')
stop=s.rfind('h')
print(s[:start+1]... |
'''
Условие
По данному натуральному n ≤ 9 выведите лесенку из n
ступенек, i-я ступенька состоит из чисел от 1 до i без пробелов.
'''
#**************************************************
n=int(input())
c=""
for i in range(1,n+1):
c+=str(i)
print(c) |
'''
Формула всего
'''
#**************************************************
import math
#print(8.9//3)
x=0
y=17
a=math.floor(((y//17)*(2**(-17*math.floor(x)-math.floor(y)//17)))//2)
#def f(x,y):
# return ((y//17)//(1 << (17*x+(y%17))))%2
#a=f(x,y)
print(a) |
'''
Условие
Процентная ставка по вкладу составляет P процентов годовых,
которые прибавляются к сумме вклада. Вклад составляет X рублей
Y копеек. Определите размер вклада через год.
Программа получает на вход целые числа P, X, Y и
должна вывести два числа: величину вклада через
год в рублях и копейках. Дробная часть... |
'''
Условие
Последовательность состоит из натуральных чисел и завершается числом 0.
Определите, сколько элементов этой последовательности равны ее наибольшему элементу.
'''
a=[]
b=0
while True:
d=int(input())
if d==0:
break
a.append(d)
for i in range(len(a)):
if max(a)==a[i]:
b+=1
pri... |
'''
Условие
Последовательность состоит из натуральных чисел и завершается числом 0.
Определите, сколько элементов этой последовательности больше предыдущего элемента.
'''
a=[]
c=0
while True:
d=int(input())
if d==0:
break
a.append(d)
for i in range(1,len(a)):
if a[i]>a[i-1]:
c+=1
print... |
'''
Условие
Шахматный слон ходит по диагонали. Даны две различные
клетки шахматной доски, определите, может ли слон попасть
с первой клетки на вторую одним ходом.
'''
#**************************************************
x1 = int(input())
y1 = int(input())
x2 = int(input())
y2 = int(input())
if abs(x1-x2)==abs(y1-y2):... |
'''
Условие
Последовательность Фибоначчи определяется так:
φ0 = 0, φ1 = 1, φn = φn−1 + φn−2.
По данному числу n определите n-е число Фибоначчи φn.
Эту задачу можно решать и циклом for.
'''
a=int(input())
b=[0,1]
if a==0:
print(0)
else:
for i in range(2,a+1):
b.append(b[i-1]+b[i-2])
c=0
pri... |
'''
Условие
В первый день спортсмен пробежал x километров, а затем он
каждый день увеличивал пробег на 10% от предыдущего значения.
По данному числу y определите номер дня, на который пробег
спортсмена составит не менее y километров.
Программа получает на вход действительные числа x и y и
должна вывести одно натур... |
'''
Условие
Дан список чисел. Выведите все элементы списка, которые больше предыдущего элемента.
'''
a = input().split()
for i in range(len(a)):
a[i] = int(a[i])
for i in range(1,len(a)):
if a[i]>a[i-1]:
print(a[i],end=' ')
|
'''
Условие
Дано число n. С начала суток прошло n минут. Определите,
сколько часов и минут будут показывать электронные часы
в этот момент. Программа должна вывести два числа:
количество часов (от 0 до 23) и количество минут (от 0 до 59).
Учтите, что число n может быть больше, чем количество минут в
сутках.
'''
#*... |
#!/usr/bin/env python3
import sys
def to_exit(jumps, offset_adjustment):
"""Count the number of steps to the exit, following the jump protocol."""
steps, i = 0, 0
while 0 <= i < len(jumps):
offset = jumps[i]
jumps[i] += offset_adjustment(offset)
i += offset
steps += 1
... |
# https://practice.geeksforgeeks.org/problems/minimum-cost-path/0
def minCost(arr, n):
tempCost = [[0 for i in range(n)] for j in range(n)]
tempCost[0][0] = arr[0][0]
for i in range(1, n):
tempCost[0][i] = tempCost[0][i-1] + arr[0][i]
for i in range(1, n):
tempCost[... |
def longestEvenOddSubarray(arr, n):
res = 1
curr = 1
for i in range(1, n):
if((arr[i-1]%2 == 0 and arr[i]%2 != 0) or (arr[i-1]%2 != 0 and arr[i]%2 == 0)):
curr += 1
res = max(res, curr)
else:
curr = 1
return res
if __name__=="__main__":
t = int(in... |
import random
class Cell:
def __init__(self, coords):
self.num_adjacent_mines = 0
self.is_mine = False
self.revealed = False
self.flagged = False
self.coords = coords
def get_visual_representation(self):
if self.flagged:
return "[F]"
if not ... |
#Day 1: Chronal Calibration
#Given a file containing frequency inputs, calculate the resulting frequency after all the changes in frequency have been applied.
#Open the file. This file comes from https://adventofcode.com/2018/day/1/input. Inputs differ per user.
frequency_inputs = open('input.txt')
#Read each line of... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.